4

I need to write a stored procudere like the following:

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;

But I don't know what type of ret_val I should declare?

1
  • I think you need to declare it as record Commented Jan 25, 2016 at 9:17

1 Answer 1

6

In a function returning a table you do not need a variable for returned value. The columns of the table are treated as OUT parameters. You can assign values to them and use RETURN NEXT, e.g.:

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Very interesting, thanks much. But could'nt you explain what OUT parameters are in a nutshell? I just haven't come across with that term before...
Read about OUT parameters here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.