在postgres中声明表类型的变量

St.*_*rio 4 sql postgresql stored-procedures

我需要编写一个存储过程,如下所示:

CREATE OR REPLACE FUNCTION foo() RETURNS TABLE(user_id integer, count bigint) AS $$
    some_array integer[];
    ret_val __WHAT_TYPE_;
BEGIN
    FOR i IN 1 .. array_upper(some_array, 1)
    LOOP
        //modify the ret_val
    END LOOP;
    RETURN ret_val;
END $$
LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

ret_val但我不知道我应该申报什么类型?

kli*_*lin 6

在返回表的函数中,不需要使用变量作为返回值。表的列被视为 OUT 参数。您可以为它们赋值并使用 RETURN NEXT,例如:

CREATE OR REPLACE FUNCTION foo() 
RETURNS TABLE(user_id integer, counts bigint) AS $$
DECLARE
    i integer;
BEGIN
    FOR i IN 1..4
    LOOP
        user_id = i;
        counts = i* i;
        RETURN NEXT;
    END LOOP;
END $$
LANGUAGE plpgsql;

SELECT * FROM foo();

 user_id | counts 
---------+--------
       1 |      1
       2 |      4
       3 |      9
       4 |     16
(4 rows)
Run Code Online (Sandbox Code Playgroud)