简体   繁体   English

PostgreSQL 创建触发器,在每次插入或更新表时运行 function

[英]PostgreSQL Create Trigger which runs a function on every insert or update of a table

I have defined two tables, scores and analyzed_avg_score , in my postgres database.我在我的 postgres 数据库中定义了两个表, scoresanalyzed_avg_score I also have a function which i declaired like that:我也有一个 function 我这样声明:

CREATE FUNCTION updateAvgScore() RETURNS void AS $$
    INSERT into analyzed_avg_score
        (SELECT 
            user,
            avg(score_value)
        FROM
            scores
        group by user) on conflict do nothing;
$$ LANGUAGE SQL;

Now, I want to have a trigger or something similar that runs this function every time I insert or update something in score .现在,我想要一个触发器或类似的东西,每次我在score中插入或更新某些东西时运行这个 function 。 I don't have a lot of experience with SQL, yet.我对 SQL 还没有很多经验。 So, does anyone have an idea how the trigger should look like?那么,有人知道触发器应该是什么样子吗?

CREATE TRIGGER SCORE_INSERT AFTER INSERT ON SCORE
FOR EACH ROW EXECUTE PROCEDURE updateAvgScore();


/*Have it return a trigger like this */

CREATE OR REPLACE FUNCTION updateAvgScore() RETURNS TRIGGER AS $example_table$
   BEGIN
      /*YOUR lOGIC HERE*/
   END;
$example_table$ LANGUAGE plpgsql;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM