Calculate number of rows affected by batch query in PostgreSQL

时光毁灭记忆、已成空白 提交于 2019-12-01 18:53:32

DO statement blocks are good to execute dynamic SQL. They are no good to return values. Use a plpgsql function for that.

The key statement you need is:

GET DIAGNOSTICS integer_var = ROW_COUNT;

Details in the manual.

Example code:

CREATE OR REPLACE FUNCTION f_upd_some()
  RETURNS integer AS
$func$
DECLARE
   ct int;
   i  int;
BEGIN
   EXECUTE 'UPDATE tbl1 ...';       -- something dynamic here
   GET DIAGNOSTICS ct = ROW_COUNT;  -- initialize with 1st count

   UPDATE tbl2 ...;                 -- nothing dynamic here 
   GET DIAGNOSTICS i = ROW_COUNT;
   ct := ct + i;                    -- add up

   RETURN ct;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM f_upd_some();
Yavanosta

My solution is quite simple. In Oracle I need to use variables to calculate the sum of updated rows because command.ExecuteNonQuery() returns only the count of rows affected by the last UPDATE in the batch.

However, npgsql returns the sum of all rows updated by all UPDATE queries. So I only need to call command.ExecuteNonQuery() and get the result without any variables. Much easier than with Oracle.

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