0

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

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、UpdateByID

我知道我必须说更新后,删除,插入`,但仅此而已。

谢谢

4

1 回答 1

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空。

于 2012-11-29T10:46:39.873 回答