How to return updated rows from function

蓝咒 提交于 2020-01-03 17:36:10

问题


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.


回答1:


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




回答2:


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;


来源:https://stackoverflow.com/questions/3940473/how-to-return-updated-rows-from-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!