How to get individual columns from table returned from a function?

前端 未结 1 569
太阳男子
太阳男子 2021-01-24 22:57

I\'m trying to make a function with returns table.

CREATE  FUNCTION karta_pacjenta(pe VARCHAR(11))
  RETURNS TABLE(\'data\' DATE,\'imie\' TEXT, \'nazwisko\' TEXT         


        
相关标签:
1条回答
  • 2021-01-24 23:24

    To decompose the rows you get back from the function treat it like any other table:

    SELECT * FROM karta_pacjenta('foo45678901');

    Functions returning a set of rows are also called "table functions".


    Aside from that, what you presented wouldn't work.

    CREATE  FUNCTION karta_pacjenta(_pe varchar)
      RETURNS TABLE(data DATE, imie TEXT, nazwisko TEXT
                  , diagnoza TEXT,przepisany lek TEXT)  AS
    $func$
    SELECT w.dzien, p.imie, p.nazwisko, ch.nazwa, l.nazwa
    FROM   pacjenci  p
    JOIN   diagnozy  d  USING (pesel) -- shorthand if columns are unambiguous
    JOIN   wizyty    w  USING (pesel)
    JOIN   choroby   ch ON ch.kod_choroby = d.kod_choroby
    JOIN   recepty   r  ON r.nr_wizyty = w.nr_wizyty
    JOIN   leki      l  ON l.kod_leku = r.kod_leku 
    WHERE  p.pesel = _pe
    $func$ LANGUAGE sql;
    
    • Single quotes for column names are a syntax error. Would have to be double-quotes. Better you always use unquoted, legal, lower case names, though.

    • Don't quote the language name, it's an identifier.

    The rest is optional, but good advise.

    • A simple SQL function does the job here.

    • Use explicit JOIN syntax. Same result, but much easier to maintain.

    • It's probably pointless to use varchar(11) instead of just varchar or text as param type. (Corner case exceptions apply.)

    • Use dollar-quoting - which is totally optional here, but generally good style to quote the function body. Sooner or later you'll want to include single quotes in the body.

    0 讨论(0)
提交回复
热议问题