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

不打扰是莪最后的温柔 提交于 2019-12-02 07:35:55

问题


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, 'diagnoza' TEXT,'przepisany lek' TEXT)  AS'  
BEGIN
 RETURN QUERY SELECT w.dzien AS dzien,p.imie, p.nazwisko, ch.nazwa, l.nazwa
 FROM pacjenci p, diagnozy d, choroby ch, wizyty w, leki l, recepty r
 WHERE p.pesel=d.pesel AND d.kod_choroby=ch.kod_choroby AND p.pesel=pe AND w.pesel=pe AND l.kod_leku=r.kod_leku AND r.nr_wizyty=w.nr_wizyty;
END;
' LANGUAGE 'plpgsql';

It works quite nice, but I need one more thing. As result of this function I get function name, and then couple of records.

But, I'd like to have column names over the records. Any idea how to do this?


回答1:


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.



来源:https://stackoverflow.com/questions/28137820/how-to-get-individual-columns-from-table-returned-from-a-function

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