如果存在不按预期工作

时间:2016-05-26 14:36:45

标签: sql postgresql

我必须在下面的函数中用我的逻辑忽略一些明显的东西。我试图在插入之前做一个,我有一个主(父)表和一个子(从master继承)。我试图检查记录是否存在,是否进行更新,否则进行插入。但是,我的IF EXISTS没有像我预期的那样工作,它总是会导致插入。

功能:

    CREATE OR REPLACE FUNCTION alerting.dataset_aggregations_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN

    IF EXISTS(SELECT 1 FROM alerting.dataset_aggregations dm
          WHERE dm.dataset = NEW.dataset AND dm.start_date_epoch = NEW.start_date_epoch) THEN

       UPDATE alerting.dataset_aggregations
           SET message_count = NEW.message_count
       WHERE dm.dataset = NEW.dataset
       AND dm.start_date_epoch = NEW.start_date_epoch;

    ELSE

      INSERT INTO alerting.dataset_aggregations(dataset, start_date,start_date_epoch, message_count) VALUES(NEW.dataset, NEW.start_date, NEW.start_date_epoch,NEW.message_count);

    END IF;

END;
$$
LANGUAGE plpgsql;

触发:

    --Before Insert Trigger
CREATE TRIGGER insert_dataset_aggregations_master
        BEFORE INSERT ON alerting.dataset_aggregations_master
        FOR EACH ROW EXECUTE PROCEDURE alerting.dataset_aggregations_insert_trigger();

示例插入(插入两次并创建两个条目):

INSERT INTO alerting.dataset_aggregations(dataset,start_date,start_date_epoch,message_count) VALUES('dataset1','2016-05-17T08:00:00.000Z',1463472000000,'500');

0 个答案:

没有答案