【问题标题】:How to declare bound cursor with customized column name in pl/pgsql如何在 pl/pgsql 中使用自定义列名声明绑定游标
【发布时间】:2018-12-10 20:55:54
【问题描述】:

我想在函数中使用游标,将表名作为函数变量,一个简单的例子是通过游标进行选择查询。

从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

任何帮助将不胜感激,非常感谢!

【问题讨论】:

    标签: postgresql plpgsql


    【解决方案1】:

    对于动态 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)
    

    【讨论】:

    • 非常感谢您的回答,但是如果我需要获取记录的一列,例如,我该怎么办? x.id ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2019-11-06
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多