2017-04-18 43 views
-1

我传递一个类型创建一个存储过程,做一个循环的过程中,这样我可以将每个信息类型

这是我喜欢的类型

create type leketo as(id integer, name text); 

功能将行插入我喜欢的类型

CREATE OR REPLACE FUNCTION getLeketo() 
    RETURNS SETOF leketo AS 
$BODY$ 
declare 
l leketo; 
begin 

l.id := 1; 
l.name := 'One'; 
return next l; 

l.id := 2; 
l.name := 'Two'; 
return next l; 


l.id := 3; 
l.name := 'Three'; 
return next l; 


l.id := 4; 
l.name := 'Four'; 
return next l; 

l.id := 5; 
l.name := 'Five'; 
return next l; 

end 
$BODY$ 
    LANGUAGE plpgsql VOLATILE; 

运行函数返回这样对我

select * from getLeketo() 

1 One 
2 Two 
3 Three 
4 Four 
5 Five 

在此过程中,我们将通过所有的行

CREATE OR REPLACE FUNCTION loopLeketo(pl leketo) 
    RETURNS void AS 
$BODY$ 
declare 
l leketo; 
begin 

for l in (select * from pl) loop 
    raise notice '----------------------------------------'; 
    raise notice 'id=%, name=%', l.id, l.name; 
end loop; 
end 
$BODY$ 
    LANGUAGE plpgsql VOLATILE; 

如果我试试这个,我得到了以下信息

DO $$ 
declare 
l leketo; 
begin 
select * from getLeketo() into l; 
PERFORM loopLeketo(l); 
end$$; 

错误:关系“PL”不存在

回答

1

您会收到该错误消息,因为中不会出现参数(在您的情况下为pl)子句,因此PostgreSQL将把pl解释为表名。

更深层的问题是,您尝试将一组值设置为单个变量,这将不起作用。您的SELECT ... INTO声明将仅将第一个结果存储在变量l中。

你不告诉我们你真的想达到什么样的,但我能想到的告诉你问题两种方式:

  1. 处理查询结果一个接一个。 PL/pgSQL的代码将看起来像:

    DEFINE 
        l leketo; 
    BEGIN 
        FOR l IN SELECT * FROM getleketo() LOOP 
         RAISE NOTICE 'id=%, name=%', l.id, l.name; 
        END LOOP; 
    END; 
    
  2. 定义getleketo()不是RETURNS SETOF leketo,但作为RETURNS refcursor,并将它返回游标的结果。然后,您可以将整个查询结果分配给类型为refcursor的变量,并将其用作loopleketo函数的参数。

    有关详细信息,请参见the documentation