获取数组函数返回

时间:2018-05-23 10:43:42

标签: sql postgresql

我想让这个函数返回一个包含此查询中所有ID(整数)的数组,但我被困在这里:

CREATE OR REPLACE FUNCTION public.all_id(
    prm_id integer)
    RETURNS SETOF integer 
    LANGUAGE 'plpgsql'
    COST 100.0
AS $function$
DECLARE
all_id integer;
-- all_id integer[]; gives an error, while integer only returns last value
BEGIN
    SELECT id
    COLLECT INTO all_id
    FROM subject_data
    WHERE sab_subject = (
        SELECT sab_subject
        FROM subject_data
        WHERE id = prm_id
        );
        RETURN NEXT all_id;
END;
$function$;

 SELECT * FROM public.all_id(1);

1 个答案:

答案 0 :(得分:1)

这是fn的一个例子:

t=# create or replace function ar() returns int[] as $$
declare ia int[];
begin
select array_agg(oid::int) into ia from pg_database;
return ia;
end;
$$ language plpgsql;
CREATE FUNCTION
t=# select * from ar();
                            ar
-----------------------------------------------------------
 {13505,16384,1,13504,16419,16816,17135,25542,25679,25723}
(1 row)

SETOF将返回“table”,语言不是字面值,因此不需要单引号,and so on ......

正如a_horse_with_no_name正确显示的那样,你不需要plpgsql。一个简单的查询将起作用:

SELECT array_agg(id) 
FROM subject_data 
WHERE sab_subject = ( 

    SELECT sab_subject 
    FROM subject_data 
    WHERE id = PRM_ID_VALUE 

)