Calculate number of rows affected by batch query in PostgreSQL

后端 未结 2 1524
[愿得一人]
[愿得一人] 2021-01-19 06:26

First of all, yes I\'ve read documentation for DO statement :) http://www.postgresql.org/docs/9.1/static/sql-do.html

So my question:

I need to execute some d

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 07:11

    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();
    

提交回复
热议问题