[英]How to declare bound cursor with customized column name in pl/pgsql
我想在表名作为函数变量的函数中使用游标,一个简单的示例是通过游标进行选择查询。
从PostgreSQL的文档中,我发现我可以使用
Declare curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
但是当我输入
declare curs1 cursor (key integer) for execute 'select ' || quote_ident(colname) || ' from ' || quote_ident(tablename);
它返回ERROR: syntax error at or near "'select '"
。
另一方面,如果我使用refcursor
编写函数,如下所示:
CREATE or replace FUNCTION cursor_hw(colname text,tablename text) RETURNS setof text AS $$
declare curs1 refcursor;
BEGIN
open curs1 for execute 'select ' || quote_ident(colname) || ' from ' || quote_ident(tablename);
for x in curs1 loop
return next x;
end loop;
END; $$ LANGUAGE plpgsql;
它将返回[42601] ERROR: cursor FOR loop must use a bound cursor variable
。
任何帮助将不胜感激,非常感谢!
对于动态SQL,您可能更喜欢简单的FOR record_variable IN EXECUTE <query>
而不是OPEN FETCH
。
CREATE or replace FUNCTION cursor_hw(colname text,tablename text)
RETURNS setof text AS
$$
DECLARE
x RECORD;
BEGIN
FOR x IN execute 'select ' || quote_ident(colname) || ' from '
|| quote_ident(tablename)
LOOP
IF x.first_name like 'D%' THEN
RETURN NEXT x;
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql;
执行
knayak=# select cursor_hw('first_name','employees');
cursor_hw
-----------
Donald
Douglas
David
Diana
Daniel
Den
David
Danielle
David
(9 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.