Counting number of updates

。_饼干妹妹 提交于 2020-01-06 05:47:09

问题


Hi Every one I created this trigger function to count number of rows affected by an update .

create table smt (
id serial primary key,
    num int
)
CREATE OR REPLACE FUNCTION count_updated()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    AS $BODY$
DECLARE 
    n int;
BEGIN 
    IF(TG_OP = 'UPDATE') THEN       
        get diagnostics n = row_count;
        insert into smt (num) values (n);
        return null;
    END IF;
END;
$BODY$;

CREATE TRIGGER count_updt
AFTER UPDATE  ON test
    FOR EACH ROW EXECUTE PROCEDURE count_updated(); 

what I want to do is store the number of updated rows of test in smt using GET DIAGNOSTICS, but when I read the content of smt table, the field which is reserved to stock the row_count is 0 even after an update. If you have any idea in-light me. Cordially.


回答1:


to just get amount of updates (and possibly compare before and after some statements, you can just

select n_tup_upd from pg_stat_all_tables where relname = 'test'

Otherwise you can use GET DIAGNOSTICS straight with update (for plpgsql) and update ... returning with CTE and count(1) for sql. using trigger, saving amount to table and selecting it looks an overhead indeed



来源:https://stackoverflow.com/questions/47038825/counting-number-of-updates

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