postgresql函数 - 获取受更新查询影响的行数

时间:2018-04-23 09:45:24

标签: sql postgresql function plpgsql postgresql-9.4

我正在编写一个执行一些更新查询的postgresql函数。我需要确保所有行都受到影响,并相应地返回成功/失败消息。

如果(受影响的行)?然后'更新成功'否则'更新失败'

如何提高通知行数?

-- Get count from UPDATE
WITH rows AS (
    UPDATE distributors
    SET dname = 'JKL Widgets'
    WHERE did <= 10
    RETURNING 1
)
SELECT count(*) FROM rows;

1 个答案:

答案 0 :(得分:1)

use get diagnostics,例如:

t=# create table so17(i int);
CREATE TABLE
t=# insert into so17 values(0);
INSERT 0 1
t=# do $$
declare d int;
begin
update so17 set i = 0 where i=0;
get diagnostics d = row_count;
raise info 'updated: % rows', d;
update so17 set i = 0 where i=1;
get diagnostics d = row_count;
raise info 'updated: % rows', d;
end;
$$;
INFO:  updated: 1 rows
INFO:  updated: 0 rows
DO