如何在 pl/pgsql 中使用自定义列名声明绑定游标

How to declare bound cursor with customized column name in pl/pgsql

我想在名称为 table 的函数中使用游标作为函数变量,一个简单的例子是通过游标的 select 查询。

从 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);

它 returns 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;

会return[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)