我有代码:
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”表,其中包含:
我想创建一个只显示列内容的游标: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;
^
我做错了什么?
答案 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两种方式减少:
使用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;
在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;
注意:如果你在一些复杂的查询中使用它而不是琐碎的话,这些函数可以阻止SQL优化器。我个人不喜欢它。请改用视图。它的工作方式与您的需求相同,优化没有风险。
CREATE VIEW facturas_cliente
AS SELECT id_clie, nom_clie
FROM cliente
ORDER BY id_clie;