0

Is there a way to create postgres stored function (using plpgsql to be able to set input parameters) that returns a custom data set?

I've tried to do something like this according to official manual:

CREATE FUNCTION extended_sales(p_itemno int)
RETURNS TABLE(quantity int, total numeric) AS $$
BEGIN
 RETURN QUERY SELECT quantity, quantity * price FROM sales
 WHERE itemno = p_itemno;
END;
$$ LANGUAGE plpgsql;

but result is an array with only one column which contains type (quantity, total), but I need to get two column array with 'quantity' column and 'total' column.

asked Dec 13, 2014 at 1:40
1
  • 3
    You need to use select * from extended_sales(...). Plus you don't need a PL/pgSQL function: sqlfiddle.com/#!12/d5aef/1 Commented Dec 13, 2014 at 7:47

1 Answer 1

2

At a guess you're running:

SELECT extended_sales(1);

This will return a composite type column. If you want it expanded, you must instead run:

SELECT * FROM extended_sales(1);

Also, as @a_horse_with_no_name notes, a PL/pgSQL function is completely unnecessary here. Presumably this is a simplified example?

In future please include:

  • Your PostgreSQL version; and
  • The exact SQL you ran and the exact output you got
answered Dec 13, 2014 at 11:18
Sign up to request clarification or add additional context in comments.

1 Comment

It definitely works right now. I take into account your recommendations about db version and sql-script in future, thank you!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.