用于删除和插入的SQL触发器

时间:2012-11-29 08:00:49

标签: sql sql-server triggers

我的触发器看起来像这样:

ALTER TRIGGER [dbo].[trSeasonHotelsSupplierOfferUpdate]
  ON  [dbo].[SeasonHotelsSupplierOffers]
  AFTER UPDATE
AS
BEGIN
  IF ((SELECT COUNT(*) FROM inserted) = 1 AND (SELECT COUNT(*) FROM deleted) = 1)
  BEGIN
       INSERT INTO SeasonHotelsSupplierOffersHistory (SeasonHotelSupplierOfferID, ColumnEN, OldValue, NewValue, UpdateDate, UpdatedByID)
         SELECT 
            i.SeasonHotelSupplierOfferID, 'Name', d.Name, i.Name, i.UpdateDate, i.UpdatedByID 
         FROM 
            inserted i, deleted d       
         WHERE 
            ISNULL(i.Name,'')<>ISNULL(d.Name,'')
    END
END

我需要为插入的数据和删除的数据做这项工作。这全部保存到名为SeasonHotelsSupplierOffersHistory的表中,该表包含以下列:

SeasonHotelSupplierOfferID,ColumnEN,OldValue,NewValue,UpdateDate,UpdatedByID

我知道我必须说更新后,删除,插入`,但这就是它。

由于

1 个答案:

答案 0 :(得分:1)

我不是100%肯定你在问什么,因为唯一的实际问题似乎是如何使触发器适用于INSERT和DELETE,但你已经在你的问题中回答了这个问题。我只能假设您正在努力将触发器插入触发器以便插入和删除。我想像这样的东西会起作用。

CREATE TRIGGER trSeasonHotelsSupplierOfferUpdate 
ON dbo.SeasonHotelsSupplierOffers
AFTER UPDATE, INSERT, DELETE
AS
BEGIN
    INSERT  SeasonHotelsSupplierOffersHistory (SeasonHotelSupplierOfferID, ColumnEN, OldValue, NewValue, UpdateDate, UpdatedByID)
    SELECT  COALESCE(inserted.SeasonHotelSupplierOfferID, deleted.SeasonHotelSupplierOfferID),
            'Name', 
            deleted.Name, 
            inserted.Name, 
            COALESCE(inserted.UpdateDate, deleted.UpdateDate),
            COALESCE(inserted.UpdatedByID, deleted.UpdatedByID)
    FROM    inserted
            FULL JOIN deleted
                ON inserted.SeasonHotelSupplierOfferID = deleted.SeasonHotelSupplierOfferID
    WHERE   COALESCE(inserted.Name, '') != COALESCE(deleted.Name, '')   -- ONLY INSERT WHERE NAME HAS CHANGED
END

您将能够识别插入,因为OldValue将为空,删除为NewValue将为空。