postgresql 添加触发器

添加触发器

 

-- 创建触发器函数
CREATE FUNCTION update_kpi_for_path_depth_trigger_fun()
returns trigger as $$
begin
    DELETE from kpi_path;
    WITH RECURSIVE T (kpi_id, NAME, PARENT_ID, PATH, DEPTH,kpi_sql)  AS (
    SELECT kpi_id, NAME, PARENT_ID, ARRAY[kpi_id] AS PATH, 1 AS DEPTH,kpi_sql
    FROM kpi
    WHERE PARENT_ID = 0 
    UNION ALL
    SELECT  D.kpi_id, D.NAME, D.PARENT_ID, T.PATH || D.kpi_id, T.DEPTH + 1 AS DEPTH,D.kpi_sql
    FROM kpi D
    JOIN T ON D.PARENT_ID = T.kpi_id
    )
    INSERT INTO kpi_path(kpi_id,name,parent_id,path,depth,kpi_sql)  SELECT kpi_id, NAME, PARENT_ID, PATH, DEPTH,kpi_sql FROM T
    ORDER BY PATH;
    UPDATE kpi set path =p.path,depth=p.depth from kpi_path p WHERE p.kpi_id=kpi.kpi_id;
        RETURN NULL;   -- 返回值是必须的
end;
$$
language plpgsql;
 -- 基于表和列创建出发器
CREATE TRIGGER update_kpi_for_path_depth_fun_trigger
after insert or UPDATE of parent_id on kpi
for each row execute procedure update_kpi_for_path_depth_trigger_fun();

 

posted @ 2019-09-06 14:51  huanglei2010  阅读(2398)  评论(0编辑  收藏  举报