【问题标题】:Update counter trigger PostgreSql更新计数器触发 PostgreSql
【发布时间】:2016-03-08 22:33:35
【问题描述】:

我有一张这样的桌子

-----------------------------------------------------------------------------------
id                                    | notification_sent | times_notification_sent
-----------------------------------------------------------------------------------
4a1717a2-6e1e-4af6-aa34-8262899aa060  | t                 | 0

这里发送的通知是布尔字段,times_notification_sent 是 int。我正在尝试创建触发器,当 notification_sent 从 true 更改为 false 时,times_notification_sent 将增加 1。

我正在使用以下函数和触发器,但它不起作用。

CREATE OR REPLACE FUNCTION update_sent_counter_for_watch()  RETURNS TRIGGER 
LANGUAGE plpgsql
AS $$ BEGIN
IF OLD.notification_sent IS TRUE AND NEW.notification_sent IS FALSE THEN
   UPDATE "watch" SET "times_notification_sent" = "times_notification_sent" + 1 WHERE "id" = OLD."id";
END IF;
END;
$$;

CREATE TRIGGER "update_times_sent_counter" AFTER UPDATE OF "times_notification_sent" ON "public"."watch"
FOR EACH ROW
WHEN (OLD.notification_sent IS DISTINCT FROM NEW.notification_sent)
EXECUTE PROCEDURE "public"."update_sent_counter_for_watch"();

【问题讨论】:

    标签: database postgresql stored-procedures triggers


    【解决方案1】:

    你有两个错误:

    您不需要update,只需分配新值:

    CREATE OR REPLACE FUNCTION update_sent_counter_for_watch()  
      RETURNS TRIGGER 
      LANGUAGE plpgsql
    AS 
    $$ 
    BEGIN
      IF OLD.notification_sent IS TRUE AND NEW.notification_sent IS FALSE THEN
        new.times_notification_sent := old.times_notification_sent + 1;
      END IF;
      RETURN new;
    END;
    $$;
    

    而且您不能更改after update 触发器中的值,您需要将其更改为before 触发器:

    CREATE TRIGGER "update_times_sent_counter" BEFORE UPDATE OF "times_notification_sent" 
      ON "public"."watch"
      FOR EACH ROW
    WHEN (OLD.notification_sent IS DISTINCT FROM NEW.notification_sent)
    EXECUTE PROCEDURE "public"."update_sent_counter_for_watch"();

    【讨论】:

    • 你们俩都是对的。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    相关资源
    最近更新 更多