如何从函数返回更新的行

发布于 2024-09-27 06:25:14 字数 622 浏览 6 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

澜川若宁 2024-10-04 06:25:14

当 PL/pgSQL 函数必须返回 setof 时,它必须使用 “返回下一个”或“返回查询”

When a PL/pgSQL function has to return setof it has to use "RETURN NEXT" or "RETURN QUERY".

·深蓝 2024-10-04 06:25:14

我终于明白了
我使用 for 循环,然后返回。
谢谢

这是我的代码

declare result table1%rowtype;
begin
 for result in update table1 set ... where ... returning * loop
  return next result;
 end loop;
end;

i finally got it
i use for loop with return next.
thanks

here's my code

declare result table1%rowtype;
begin
 for result in update table1 set ... where ... returning * loop
  return next result;
 end loop;
end;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文