2

I want to return the whole table with stored procedure not function

my code is:

CREATE OR REPLACE PROCEDURE public.test()

RETURN TABLE (
     id   numeric
   , test varchar
   ) AS  -- Results  -- remove this
$func$

BEGIN
    RETURN QUERY
    SELECT * 
    FROM public.test

END
$func$ LANGUAGE plpgsql;

but its not works.

1 Answer 1

11

Stored procedures aren't meant to return anything, use a function. And you don't need PL/pgSQL for that either:

create or replace FUNCTION public.test()
  returns TABLE (id   numeric, test varchar) 
AS
$func$
  SELECT * 
  FROM public.test;
$func$ 
LANGUAGE sql;

As you return all columns of one table, you can also use returns setof

create or replace FUNCTION public.test()
  returns setof public.test
AS
$func$
  SELECT * 
  FROM public.test;
$func$ 
LANGUAGE sql;

Then use it like a table:

select *
from test();
Sign up to request clarification or add additional context in comments.

5 Comments

I appreciate your answer but I want CREATE OR REPLACE PROCEDURE not create or replace FUNCTION.
@KrunalPandya: that's not how Postgres works. Procedures are not intended to return results sets. Use a function for that.
What is the particular reason why a procedure instead of a function? A function is the correct way to do this. IMHO Two of the worst words in development: "I want", three of worst words: "I don't want". Especially without a good well defined reason.
@Belayer: the reason is probably "Because we have always done it that way in SQL Server"
I've just started looking at postgres coming from a TSQL background and I wondered, if procedures aren't supposed to return results why not always use functions? (procedures seem almost like a trigger to me [in TSQL context])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.