加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL获取操作影响的行数

发布时间:2020-12-13 17:24:48 所属栏目:百科 来源:网络整理
导读:如何来获取普通的操作所影响的行数,PostgreSQL里面有一个内置的变量DIAGNOSTICS与ROW_COUNT可以做到这一点。 一、环境: DB:9.4beta3 二、准备: postgres=# create table test(id int);CREATE TABLEpostgres=# insert into test select generate_series(1,2
如何来获取普通的操作所影响的行数,PostgreSQL里面有一个内置的变量DIAGNOSTICS与ROW_COUNT可以做到这一点。

一、环境:
DB:9.4beta3

二、准备:
postgres=# create table test(id int);
CREATE TABLE
postgres=# insert into test select generate_series(1,20);
INSERT 0 20
postgres=# select * from test;
 id 
----
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
(20 rows)
三、创建函数:
CREATE OR REPLACE FUNCTION fun_affect_rows()
  RETURNS text AS
$BODY$

declare
v_count int;begin

insert into test values(99),(98);
GET DIAGNOSTICS v_count = ROW_COUNT;
raise notice '本次插入数据量 %',v_count;

delete from test where id < 15;
GET DIAGNOSTICS v_count = ROW_COUNT;
raise notice '本次删除数据量 %',v_count;

update test set id = 100 where id >90;
GET DIAGNOSTICS v_count = ROW_COUNT;
raise notice '本次更新数据量 %',v_count;

return '测试完毕';
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION fun_affect_rows()
  OWNER TO postgres;
四、运行情况:
postgres=# select * from fun_affect_rows();
NOTICE:  本次插入数据量 2
NOTICE:  本次删除数据量 14
NOTICE:  本次更新数据量 2
 fun_affect_rows 
-----------------
 测试完毕
(1 row)
如果要返回DML的结果,那就用returning就可以了

五、参考
http://www.postgresql.org/docs/9.0/static/plpgsql-statements.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读