PostgreSQL游标错误

时间:2015-01-18 05:23:49

标签: postgresql cursor plpgsql

我有代码:

 DECLARE 
      cliente_cursor CURSOR FOR SELECT * FROM cliente;
      cliente cliente.id_clie%TYPE;
      nom cliente.nom_clie%TYPE;  
    BEGIN
      OPEN cliente_cursor;
      FETCH cliente_cursor INTO cliente, nom;

但我无法运行它。出现以下错误:

ERROR: syntax error at or near "cliente"
LINE 3: cliente cliente.id_clie% TYPE;
        ^

我有“cliente”表,其中包含:

Table cliente

我想创建一个只显示列内容的游标:id_clie,上一个表的nom_clie。

我也用过:

create or replace function facturas_cliente()
  returns table (a int, b character varying(40))
  language plpgsql as $$
declare 
  x cliente%rowtype ;
  cliente_cursor cursor for select id_clie, nom_clie from cliente 
  order by id_clie;
begin
  for x in cliente_cursor loop
    return next x;
  end loop;
end $$;

但我收到错误:

ERROR: RETURN NEXT can not have parameters in a function with OUT parameters
LINE 9: return next x;
                    ^

我做错了什么?

1 个答案:

答案 0 :(得分:1)

第一个问题很奇怪。我在PostgreSQL 9.5上测试过(但相同的代码应该适用于9.2及更高版本):

CREATE TABLE cliente(id_clie int, tel_clie varchar(15), dir_clie varchar(15));

DO $$
DECLARE
  cliente_cursor CURSOR FOR SELECT * FROM cliente;
  cliente cliente.id_clie%TYPE;
  tel cliente.tel_clie%TYPE;
BEGIN
  OPEN cliente_cursor;
END;
$$;

它没有任何问题。它看起来像是一些错误的错误。

第二个问题很清楚。当函数具有OUT个变量或被声明为TABLE函数时,RETURN NEXT必须没有表达式。返回的复合值基于OUT变量的实际上下文(TABLE子句中声明的列也是OUT个变量)。你的代码应该是:

create or replace function facturas_cliente() 
returns table (a int, b character varying(40))
language plpgsql as $$
declare 
  cliente_cursor cursor for select id_clie, nom_clie 
                            from cliente 
                            order by id_clie;
  r record;
begin
  for r in cliente_cursor -- a,b ~ OUT var declared in TABLE() clause
  loop
    a := r.id_clie; b := r.nom_clie; 
    return next;  -- not: return next x;
  end loop;
end $$;

这个代码可以用PL / pgSQL两种方式减少:

  1. 使用SQL函数

    create or replace function facturas_cliente() 
    returns table (a int, b character varying(40))
    language sql as $$
      select id_clie, nom_clie from cliente order by id_clie;
    $$ language plpgsql;
    
  2. 在plpgsql中使用RETURN QUERY语句:

    create or replace function facturas_cliente() 
    returns table (a int, b character varying(40))
    language sql as $$
    BEGIN
       RETURN QUERY SELECT id_clie, nom_clie 
                    FROM cliente 
                    ORDER BY id_clie;
       RETURN;
    END;
    $$ language plpgsql;
    
  3. 注意:如果你在一些复杂的查询中使用它而不是琐碎的话,这些函数可以阻止SQL优化器。我个人不喜欢它。请改用视图。它的工作方式与您的需求相同,优化没有风险。

    CREATE VIEW facturas_cliente
       AS SELECT id_clie, nom_clie 
          FROM cliente 
          ORDER BY id_clie;