我的更新触发器:
declare @NewValue NVARCHAR(4000) = '';
declare @OldValue NVARCHAR(4000) = '';
select @OldValue =''
+ CASE WHEN i.Name <> d.Name THEN '"Name": "'+ d.Name +'", ' ELSE '' END+
+ CASE WHEN i.Address1 <> d.Address1 THEN '"Address1": "'+ d.Address1 +'", ' ELSE '' END+
'' FROM
inserted i
JOIN deleted d on (i.AccountId = d.AccountId) ;
select @NewValue = ''
+ CASE WHEN d.Name = NULL OR i.Name <> d.Name THEN '"Name": "'+ i.Name +'", ' ELSE '' END+
+ CASE WHEN d.Address1 = NULL OR i.Address1 <> d.Address1 THEN '"Address1": "'+ i.Address1 +'", ' ELSE '' END+
'' FROM
inserted i
JOIN deleted d on (i.AccountId = d.AccountId) ;
if @NewValue <> '' AND @OldValue <> '' AND @NewValue <> @OldValue
INSERT INTO Auditlog (OtherId, TableName, ActionDate, ActionBy, Operation, ActionType)
SELECT
i.AccountId, 'Accounts', getdate(), '', 'Update', ''
FROM
inserted i
INSERT INTO AuditlogDetails (AuditlogId, OldValue , NewValue)
values (IDENT_CURRENT('dbo.Auditlog'), N'[{'+ @OldValue +'}]', N'[{'+ @NewValue +'}]')
但是这个触发器只是插入表AuditlogDetails而@NewValue是NULL:例如我有一个记录名=&#34; abc&#34;,地址1 = NULL当我更新该记录时Address1 =&#34; adasf&#34 ;然后@NewValue为NULL我希望@NewValue是[{&#34;地址1&#34;:&#34; adasf&#34;}]有人帮助我
答案 0 :(得分:1)
更改您的NULL比较
select @NewValue = ''
+ CASE WHEN d.Name = NULL OR i.Name <> d.Name THEN '"Name": "'+ i.Name +'", ' ELSE '' END+
+ CASE WHEN d.Address1 = NULL OR i.Address1 <> d.Address1 THEN '"Address1": "'+ i.Address1 +'", ' ELSE '' END+
'' FROM
inserted i
JOIN deleted d on (i.AccountId = d.AccountId) ;
在上面的行中,您比较了d.Name = NULL
和d.Address1 = NULL
。 Null是我们不知道的东西。因此,您无法将NULL与等号进行比较。
前:
Declare @var varchar(20) = NULL;
IF (@var = NULL)
BEGIN
PRINT 'Equals work'
END
IF (@var IS NULL)
BEGIN
PRINT 'IS NULL WORK'
END
但是当我们使用属性SET ANSI_NULLS (Transact-SQL)
时,上述行为将会改变将其更改为d.Name is NULL
。 d.Address1 is NULL