我想在函数中使用游标,将表名作为函数变量,一个简单的例子是通过游标进行选择查询。
从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)