从游标PostgreSQL中获取行

Mik*_*rez 3 postgresql cursor

我有光标代码:

BEGIN;
DECLARE cliente_cursor 
CURSOR FOR SELECT * FROM cliente;
Run Code Online (Sandbox Code Playgroud)

我想阅读表'cliente'中的所有内容:

表客户

使用游标.我有适用于SQL Server的代码:

DECLARE cliente_cursor CURSOR
      FOR SELECT * FROM cliente
OPEN cliente_cursor
FETCH NEXT FROM cliente_cursor;
While @@FETCH_STATUS=0
BEGIN
     FETCH NEXT FROM cliente_cursor;
End
CLOSE cliente_cursor
DEALLOCATE cliente_cursor
Run Code Online (Sandbox Code Playgroud)

我希望有一个适用于PostgreSQL的代码.

我一直在寻找解决方案,看到人们通常建议使用功能.我想知道这个PostgreSQL DBMS中是否有任何方法可以创建与SQL Server中的代码类似的东西.

我写了这段代码:

CREATE OR REPLACE FUNCTION MyFunction()
RETURNS setof cliente AS $$
DECLARE 
cursor_cliente CURSOR FOR SELECT * FROM cliente;
rec cliente%ROWTYPE;
 BEGIN
 OPEN cursor_cliente;
loop
--fetch the table row inside the loop
FETCH cursor_cliente INTO rec;
-- check if there is no record
   --exit from loop when record not found
   if not found then
        exit ;
   end if;
end loop;
RETURN;
END;
$$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我只得到:

select MyFunction();
Run Code Online (Sandbox Code Playgroud)

知道代码应该是什么?

结果

任何帮助将不胜感激!

Jas*_*sen 5

CREATE OR REPLACE FUNCTION foo() RETURNS setof cliente 
   language plpgsql AS $$
DECLARE
  x cliente%rowtype ;
BEGIN 
  FOR x IN SELECT * FROM cliente loop
    RETURN NEXT x;
  END loop;
END $$;

SELECT * FROM foo();
Run Code Online (Sandbox Code Playgroud)

它也可以用显式游标完成.

CREATE OR REPLACE FUNCTION foo() RETURNS setof cliente
  language plpgsql as $$
DECLARE 
  x cliente%rowtype ;
  cliente_cursor CURSOR FOR SELECT * FROM cliente; 
BEGIN
  FOR x IN cliente_cursor loop
    RETURN NEXT x;
  END loop;
END $$;

SELECT * FROM foo();
Run Code Online (Sandbox Code Playgroud)

该函数将持续存在,因此要么给它一个有用的名称并保留它或在完成后删除它.

如果您希望该功能的私人名称 pg_temp.foo将是您的会话专用.