我有一个 plpgsql 函数,它充当几个其他函数的包装器,所有这些函数都设置返回不同数据类型的函数。通过这个函数,我试图获得一个通用的集合返回函数,它可以返回任何数据类型的集合。记录的数据类型根据输入的表名和列名决定。
这是代码片段:
create function cs_get(tablename text, colname text) returns setof record as $$
declare
type_name text;
ctype text;
loadfunc text;
result record;
begin
select data_type into type_name from information_schema.columns where table_name = tablename and column_name = colname;
if type_name is null then
raise exception 'Table % doesnot exist or does not have attribute % ',tablename, colname;
end if;
ctype := cs_get_ctype(type_name);
loadfunc := 'select * from cs_get_'||ctype||'('''||tablename||''','''||colname||''')';
for result in execute loadfunc loop
return next result;
end loop;
return;
end; $$ language plpgsql;
假设列的类型为整数(对应的c类型为int64),loadfunc将为
select * from cs_get_int64(tablename, colname)
cs_get_int64 是一个在 C 库中定义的集合返回函数,它返回 int64
类型的值。
但是,这会出现错误
ERROR: a column definition list is required for functions returning "record" at character 15
实现此目的的最简单方法是为每种数据类型返回一个文本集
。但这当然不是一个干净的方法。我尝试用
loadFunc
select cs_get_int64::integer from cs_get_int64(tablename, colname)
这是使用记录所必需的。但是,这并没有帮助。
我现在的问题是: 是否可以创建这样一个通用的集合返回函数?如果是,怎么办?
最佳答案
答案是是。但这并非小事。
只要您返回匿名记录(返回记录集
),返回的记录就需要一个列定义列表才能在 SQL 中使用它。错误消息大致如此。
有一个(有限的)方法可以解决这个问题:polymorphic types :
CREATE OR REPLACE FUNCTION cs_get(_tbl_type <b>anyelement</b>, _colname text)
RETURNS SETOF <b>anyelement</b> AS
...
此相关答案的详细解释(最后一章的高潮!):
关于sql - 通用集合返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27066906/