Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: return a select statement in a procedure

Is there any equivalent from MSSQL to PostgreSQL to return a select statement (which result could be from various tables)? In MSSQL it would be like this:

CREATE PROCEDURE MyProc
AS
BEGIN
   SELECT * FROM MyTable
END

MyTable can be any table in MSSQL but in PostgreSQL I have to define from which table I want to return. Like this:

CREATE FUNCTION MyFunction ()
RETURNS setof "MyTable" AS $$
BEGIN
  RETURN QUERY SELECT * FROM "MyTable"
END;
$$ LANGUAGE plpgsql;

But what I want to do is return the result from a table which is passed by a param (of course my procedure is more complex and my intention why to do that is not that simple, this is only an abstract).

like image 245
kinske Avatar asked May 17 '26 22:05

kinske


1 Answers

It is more complex in Postgres, but there is a way with polymorphic types:

CREATE OR REPLACE FUNCTION f_data_of(_tbl_type anyelement)
  RETURNS SETOF anyelement AS
$func$
BEGIN

RETURN QUERY EXECUTE 'SELECT * FROM ' || pg_typeof(_tbl_type);

END
$func$ LANGUAGE plpgsql;

Call (important!):

SELECT * FROM f_data_of(NULL::"MyTable");

Detailed explanation in this related answer (see last paragraph: Various complete table types):

  • Refactor a PL/pgSQL function to return the output of various SELECT queries
like image 100
Erwin Brandstetter Avatar answered May 20 '26 14:05

Erwin Brandstetter