在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