我想编写一个返回'flattened'对象的存储过程。通过'flattening',我实际上是选择一组行,并将行中的特定字段返回到函数返回的数据中。
下面的代码解释了我要做的事情
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
我有两个问题:
答案 0 :(得分:1)
我是否正确访问了行(使用数组索引)?
不,你需要使用游标遍历结果,这在手册中有很好的解释: http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING
这样的事情应该有效:
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;
顺便说一句:拥有一个名为“user”的表并不是一个好主意,因为用户是一个保留字,从长远来看可能会导致一些问题。