如何从函数返回更新的行
我对 postgres 很陌生。我想创建一个函数(如存储过程)来更新多行并选择受影响的行。
这是我的声明:
CREATE or replace FUNCTION set_val(
_val character varying(100) ) --5
RETURNS setof "table_test" AS
$body$
declare results "table_test"%rowtype;
begin
update "table_test"
set "value" = $1
where "gender" = 'm'
returning * into results;
if not found then
insert into "table_test"("value")
values($1)
returning * into results;
end if;
return next results;
end;
$body$
LANGUAGE 'plpgsql' ;
只要只有 1 行受到影响,它就可以正常工作。但当更多行受到影响时,它就不会了。
i'm quite new to postgres. i want to create a function (like stored procedure) that updates multiple rows and selects affected rows.
here is my statement:
CREATE or replace FUNCTION set_val(
_val character varying(100) ) --5
RETURNS setof "table_test" AS
$body$
declare results "table_test"%rowtype;
begin
update "table_test"
set "value" = $1
where "gender" = 'm'
returning * into results;
if not found then
insert into "table_test"("value")
values($1)
returning * into results;
end if;
return next results;
end;
$body$
LANGUAGE 'plpgsql' ;
it works fine as long as only 1 row was affected. but when more rows are affected, it doesn't.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 PL/pgSQL 函数必须返回 setof 时,它必须使用 “返回下一个”或“返回查询”。
When a PL/pgSQL function has to return setof it has to use "RETURN NEXT" or "RETURN QUERY".
我终于明白了
我使用 for 循环,然后返回。
谢谢
这是我的代码
i finally got it
i use for loop with return next.
thanks
here's my code