Postgre Function returning output

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Srigaddam
    New Member
    • Dec 2018
    • 1

    Postgre Function returning output

    Hello,

    I am new to PostgreSQL and i would like to achieve the same result as a stored procedure in MSSQL returns.

    In SQL i can return the output of the query with out defining any return type.

    Eg: Create procedure mysp (table_name varchar(25)
    as
    begin

    if table_name = 'Color'
    select * from color;
    end

    if table_name='com pany'
    select * from company;

    End

    Here there may be any number of columns in color and company tables.

    i would like to achieve the same in postgre SQL by using functions. I believe Postgres do now support creating stored procedure as SQL.

    Thanks in Advance
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    When saying "In SQL i can return the output of the query with out defining any return type."

    The docs say: "There are three ways of returning data from a procedure to a calling program: result sets, output parameters, and return codes. This topic provides information on the three approaches. "

    May I draw the conclusion that a return type IS defined (explicitly by MS-SQL)?

    Because you example is 'bad-database-design', this is not possible in PostgreSQL, see function-returns-table
    Here is is needed to specify which fields are returned.


    P.S. Yes I will not say why I think above is 'bad-database-design'!

    Comment

    • Yasin TATAR
      New Member
      • Dec 2018
      • 3

      #3
      CREATE OR REPLACE FUNCTION get_table(g_tab le_name character varying)
      RETURNS SETOF record
      LANGUAGE plpgsql
      AS $function$
      Declare
      l_sonuc RECORD;
      BEGIN

      For l_sonuc In
      EXECUTE 'Select * from '||g_table_name ||' limit 10'
      Loop

      RETURN NEXT l_sonuc;

      End loop;

      END;
      $function$
      -----------------------------------------------------------
      SELECT * FROM get_table('tb_c ustomer') as (id Integer, name Varchar, las_name varchar);

      **** remember to write the name and type of the returned values

      Comment

      Working...