在pg中,廣泛的使用了表函數代替視圖,返回集合有兩種定義,setof和table。他們的區別在於table明確定義了字段名和類型,如下:
CREATE FUNCTION events_by_type_1(text) RETURNS TABLE(id bigint, name text) AS $$ SELECT id, name FROM events WHERE type = $1; $$ LANGUAGE SQL STABLE;
而setof則依賴SQL編譯器解析,如下:
CREATE FUNCTION events_by_type_2(text) RETURNS SETOF record AS $$ SELECT id, name FROM events WHERE type = $1; $$ LANGUAGE SQL STABLE;
使用的時候要明確as一把,如下:
SELECT * from events_by_type_2('social') as (id bigint, name text);
否則會提示"ERROR: a column definition list is required for functions returning "record""。
另外一種方式是不要返回record而是具體的類型,例如:
CREATE TYPE footype AS (score int, term text); CREATE FUNCTION foo() RETURNS SETOF footype AS $$ SELECT * FROM ( VALUES (1,'hello!'), (2,'Bye') ) t; $$ language SQL immutable; SELECT * FROM foo();
在pg 10+新版本中,本質上沒有區別。return setof my_type會更合適一些,它鼓勵重用類型、而不是隨意的拼接。
https://stackoverflow.com/questions/22423958/sql-function-return-type-table-vs-setof-records