更新计数器触发PostgreSql

时间:2016-03-08 22:33:36

标签: database postgresql stored-procedures triggers

我有一张这样的表

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

1 个答案:

答案 0 :(得分: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 triger中的值,您需要将其更改为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"();