所以我创建了一个触发器,用于比较之前和之后的更新,并确定where子句中指定的特定字段是否已更改。如果是这样,我将先前信息的快照插入历史表中。
问题是当使用空值创建字段时(给定业务规则,它合法地为null),并且在进行更新时,它无法评估字符串不等于空值。我想抓住它被发送给我们空了,然后填写。
我应该使用什么方法来比较空字段而不影响性能?
这适用于SQL Server 2005
CREATE TRIGGER [prj].[TRG_Master_Projection_Upd_History] ON [prj].[Master_Projections]
AFTER UPDATE
AS
SET NOCOUNT ON -- Prevents the error that gets thrown after inserting multiple records
-- if multiple records are being updated
BEGIN
INSERT INTO prj.History_Projections (ProjectionID, Cancelled, Appeal, Description, Response_PatternID,
Proj_Mail_date, [3602_Mail_Date], Proj_Qty, [3602_Qty], Proj_Resp_Rate,
Bounce_Back, Nickels, Kits, Oversized_RE, ChangeComments,
Modification_Process, Modification_Date, Modification_User)
SELECT D.ProjectionID, D.Cancelled, D.Appeal, D.Description, D.Response_PatternID, D.Proj_Mail_Date,
D.[3602_Mail_Date], D.Proj_Qty, D.[3602_Qty], D.Proj_Resp_Rate, D.Bounce_Back, D.Nickels, D.Kits,
D.Oversized_RE, D.ChangeComments, D.Modification_Process, D.Modification_Date, D.Modification_User
FROM deleted as D
JOIN inserted as I
ON D.ProjectionID = I.ProjectionID
WHERE (I.Cancelled <> D.Cancelled
OR I.Appeal <> D.Appeal
OR I.Description <> D.Description
OR I.Response_PatternID <> D.Response_PatternID
OR I.Proj_Mail_Date <> D.Proj_Mail_Date
OR I.[3602_Mail_Date] <> D.[3602_Mail_Date]
OR I.Proj_Qty <> D.Proj_Qty
OR I.[3602_Qty] <> D.[3602_Qty]
OR I.Proj_Resp_Rate <> D.Proj_Resp_Rate
OR I.Bounce_Back <> D.Bounce_Back
OR I.Nickels <> D.Nickels
OR I.Kits <> D.Kits
OR I.Oversized_RE <> D.Oversized_RE )
END;
SET NOCOUNT OFF;
答案 0 :(得分:3)
不幸的是,你真的必须使用哨兵值
ISNULL(I.Response_PatternID, 0) <> ISNULL(D.Response_PatternID, 0)
不幸的是没有魔法:你必须比较每个值才能看到任何差异。
如果这样说,你只触摸INSERTED和DELETED表,因此不会触及主表。除非您的更新对行有影响10000,否则它将运行正常。
您也可以使用OR,但这很麻烦
(I.Response_PatternID <> D.Response_PatternID OR I.Response_PatternID IS NULL AND I.Response_PatternID IS NOT NULL OR I.Response_PatternID IS NOT NULL AND I.Response_PatternID IS NULL)
我坚持使用ISNULL来避免COALESCE
的细微数据类型问题