0

我有这个触发器可以正常工作(据我的测试可以看出),但我强烈怀疑我可以通过使用 IF UPDATE 来简化代码......我只是不完全理解它是如何工作的。我似乎在插入和删除表方面做得最好。

可以按照我刚才提到的方式(或任何其他提高可读性的方式)简化此触发器吗?

CREATE TRIGGER [dbo].[tr_Affiliate_IU] 
   ON  [dbo].[Affiliate] 
   AFTER INSERT, UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Get the current date.
    DECLARE @getDate DATETIME = GETDATE()

    -- Set the initial values of date_created and date_modified.
    UPDATE
        dbo.Affiliate
    SET 
         date_created = @getDate
    FROM
        dbo.Affiliate A 
        INNER JOIN INSERTED I ON A.id = I.id
        LEFT OUTER JOIN DELETED D ON I.id = D.id
    WHERE
        D.id IS NULL

    -- Ensure the value of date_created does never changes.
    -- Update the value of date_modified to the current date.
    UPDATE
        dbo.Affiliate
    SET
         date_created = D.date_created
        ,date_modified = @getDate
    FROM 
        dbo.Affiliate A 
        INNER JOIN INSERTED I ON A.id = I.id
        INNER JOIN DELETED D ON I.id = D.id 
END
4

1 回答 1

3

如果 updated(column_name) 无济于事,因为它只是说明该列参与了引发触发器的查询。触发器的更新部分可以通过使用 case 语句来缩短,以帮助确定 date_created 将保留哪个日期。

CREATE TRIGGER [dbo].[tr_Affiliate_IU] 
   ON  [dbo].[Affiliate] 
   AFTER INSERT, UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Get the current date.
    DECLARE @getDate DATETIME = GETDATE()

    -- Set the initial values of date_created and date_modified.
    UPDATE
        dbo.Affiliate
    SET 
      -- If there is a record for this ID in Deleted
         date_created = case when D.id is not null 
                          -- Take date of creation from Deleted
                             then D.date_created 
                             else @getDate 
                             end
        ,date_modified = @getDate
    FROM
        dbo.Affiliate A 
        INNER JOIN INSERTED I ON A.id = I.id
        LEFT OUTER JOIN DELETED D ON I.id = D.id
END
于 2012-04-10T23:44:53.553 回答