Arrays 复合类型的循环作为存储过程输入PostgreSQL
我通过传递一个类型来创建一个存储过程,并在该过程中执行循环,以便插入每个信息类型 这是我喜欢的类型Arrays 复合类型的循环作为存储过程输入PostgreSQL,arrays,postgresql,stored-procedures,types,plpgsql,Arrays,Postgresql,Stored Procedures,Types,Plpgsql,我通过传递一个类型来创建一个存储过程,并在该过程中执行循环,以便插入每个信息类型 这是我喜欢的类型 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;
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”不存在您会收到该错误消息,因为查询的
FROM
子句中不能出现参数(在您的情况下是pl
),因此PostgreSQL将pl
解释为表名
更深层次的问题是,您试图将一组值分配给单个变量,这将不起作用。您的选择。。。INTO
语句只将第一个结果存储在变量l
中
你没有告诉我们你真正想要实现什么,但我可以想出两种方法来解决你提出的问题:
DEFINE
l leketo;
BEGIN
FOR l IN SELECT * FROM getleketo() LOOP
RAISE NOTICE 'id=%, name=%', l.id, l.name;
END LOOP;
END;
getleketo()
不是因为返回SETOF leketo
,而是因为返回refcursor
,并让它为结果返回一个光标。然后,您可以将整个查询结果分配给refcursor
类型的变量,并将其用作loopleketo
函数的参数
有关详细信息,请参阅