How to get the number of rows affected by the normal operation, PostgreSQL inside has a built-in variable diagnostics and Row_count can do this.
First, the environment:
Db:9.4beta3
Second, prepare:
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)
Third, create the function:
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 ‘The amount of data inserted this time%’, v_count;
delete from test where id <15;
GET DIAGNOSTICS v_count = ROW_COUNT;
raise notice ‘the amount of data deleted this time%’, v_count;
update test set id = 100 where id> 90;
GET DIAGNOSTICS v_count = ROW_COUNT;
raise notice ‘the amount of data this update%’, v_count;
return ‘Test completed’;
end;
$ BODY $
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION fun_affect_rows ()
OWNER TO postgres;
Four, operation situation:
postgres = # select * from fun_affect_rows ();
NOTICE: The amount of data inserted this time 2
NOTICE: The amount of data deleted this time 14
NOTICE: The amount of data updated this time 2
fun_affect_rows
-----------------
Test finished
(1 row)
If you want to return the results of DML, then use returning.
v. References
Http://www.postgresql.org/docs/9.0/static/plpgsql-statements.html
The number of rows affected by the PostgreSQL fetch operation