INSERT触发器不触发更新?

时间:2013-04-06 14:10:05

标签: sql tsql triggers

好的,我有一个相当基本的触发器:

单词,插入后,获取IP信息并使用新数据更新已插入的行

CREATE TRIGGER [BasicData.IPInfo.Gather]
ON [BasicData]
AFTER INSERT
AS
BEGIN
    DECLARE @City VARCHAR(1000),
        @Country VARCHAR(1000),
        @IP VARCHAR(1000),
        @ROWID UNIQUEIDENTIFIER

    SELECT @IP=[IP],@ROWID=[ID] FROM [inserted]

    SELECT @Country = [Country], @City= [City]
    FROM [IPInfo] WHERE [IP] = @IP

    IF (@City IS NOT NULL) AND (@Country IS NOT NULL)
        BEGIN -- Never seems to fire
            UPDATE [BasicData]
            SET [IPCountry]=@Country,[IPCity]=@City
            WHERE [ID] = @ROWID
        END
    ELSE
        BEGIN -- Fired correctly
            INSERT INTO [IPInfo.Missing] VALUES (@IP)
        END
END

现在的问题是,它正确地添加了缺失的IP信息(仅在丢失时),但是,它似乎没有更新表格,我缺少什么?

我已经用一切可能的方式调整了它......(我的触发器知识相当糟糕)

1 个答案:

答案 0 :(得分:0)

有一些问题:

  1. INSERTED可以包含很多行。您的触发器只允许一个。
  2. 触发器是AFTER INSERT,我猜这可能会排除UPDATE。试试AFTER INSERT, UPDATE
  3. 您的IF语句未检查UPDATE - 如果列已更新为NULL,该怎么办?即使它是一个更新,它也不会捕获它。如果插入NON NULL数据怎么办?它会认为这是一个更新。
  4. 据我所知,识别UPDATE的唯一方法是在PK上加入INSERTED和`DELETED。如果匹配,则会更新。

    也许你可以像这样重写它:

    CREATE TRIGGER [BasicData.IPInfo.Gather]
    ON [BasicData]
    AFTER INSERT, UPDATE
    AS
    BEGIN
    
    -- Save UPDATES to BasicData
    UPDATE [BasicData]
    SET [IPCountry]=I.Country,[IPCity]=I.City
    FROM [BasicData] UT
    INNER JOIN
    [inserted] I
    ON I.ID = UT.ID
    INNER JOIN
    Deleted D
    ON D.ID = I.ID
    INNER JOIN
    [IPInfo] IP
    ON I.ID = IP.ID
    
    -- Save inserts to Missing
    INSERT INTO [IPInfo.Missing] (IP)
    SELECT IP FROM
    INSERTED I
    WHERE NOT EXISTS (SELECT 1 FROM DELETED D WHERE D.ID = I.ID)
    
    END