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
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.