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

巧了我就是萌 提交于 2019-12-02 05:11:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!