开发者

How to write this pl/pgsql function?

开发者 https://www.devze.com 2023-02-02 01:54 出处:网络
I want to write a stored procedure that returns a \'flattened\' object. By \'flattening\', I am essentially selecting a set of rows, and returning specific fields in the rows, into the data returned f

I want to write a stored procedure that returns a 'flattened' object. By 'flattening', I am essentially selecting a set of rows, and returning specific fields in the rows, into the data returned from the function.

The code below explains what I am trying to do

CREATE TABLE user (id int, school_id int, name varchar(32));

CREATE TYPE my_type (user1_id int, user1_name varchar(32), user2_id int, user2_name varchar(32));

CREATE OR REPLACE FUNCTION get_two_users_from_school(schoolid int)
RETURNS my_type AS $$
DECLARE
 result my_type
 temp_result user
BEGIN
  -- for purpose of this question assume 2 rows returned
  SELECT id, name INTO temp_result FROM user where school_id = schoolid LIMIT 2;
  -- Will the (pseudo)code below work?:
  result.user1_id := temp_result[0].id ;
  result.user1_name := temp_result[0].name ;
  result.user2_id := temp_result[1].id ;
  result.user2_name := temp_result[1].name ;
  return result ;
END
$$ language plpgsql

I have two questions:

  • Am I using the correct data type for variable temp_result
  • Am I accessing the rows correctly (开发者_开发百科using array indexing)?


Am I accessing the rows correctly (using array indexing)?

No, you need to loop through the result using a cursor which is nicely explained in the manual: http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING

Something like this should work:

DECLARE 
  temp_result RECORD;
  row_counter integer;
BEGIN
  row_counter := 1;
  FOR temp_result IN SELECT id, name FROM user where school_id = schoolid LIMIT 2 LOOP
    IF row_counter = 1 THEN
       result.user1_id := temp_result.id;
       result.user1_name = temp_result.name;
    END IF;
    IF row_counter = 2 THEN
       result.user2_id := temp_result.id;
       result.user2_name = temp_result.name;
    END IF;
    row_counter := row_counter + 1;
  END LOOP;

  return result;
END;

Btw: having a table named "user" is not a really good idea as user is a reserved word and might cause some problems in the long run.

0

精彩评论

暂无评论...
验证码 换一张
取 消