好的,我有一个相当基本的触发器:
单词,插入后,获取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信息(仅在丢失时),但是,它似乎没有更新表格,我缺少什么?
我已经用一切可能的方式调整了它......(我的触发器知识相当糟糕)
答案 0 :(得分:0)
有一些问题:
AFTER INSERT, UPDATE
据我所知,识别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