我正在创建一个触发器,我想在编辑行时解析Deleted和Inserted的所有列。因此,如果删除的col1与插入的col1不同,则将此更改存储在另一个表中。以下是我如何实现这一目标,但我想让它变得充满活力。
if not exists (select * from deleted d join inserted i on d.Cisitid = i.Cisitid ) and @Action in ('U') -- UpdateCisitid
BEGIN
select @audit_oldvalue = Cisitid from deleted;
select @audit_value = Cisitid from inserted;
insert into [dbo].[AuditTrailCTables]([TSid],[TableName],[TSField],[OldValue],[NewValue],[changedate],[Change_Action],[Change_user],[Columns_Updated])
select Cisitid,@tablename,'Cisitid', @audit_oldvalue, @audit_value,getdate(),@Action, coalesce(ModifiedBy,suser_name()), 'Cisitid'
from inserted
--Cformid
select @audit_oldvalue = Cformid from deleted;
select @audit_value = Cformid from inserted;
insert into [dbo].[AuditTrailCTables]([TSid],[TableName],[TSField],[OldValue],[NewValue],[changedate],[Change_Action],[Change_user],[Columns_Updated])
select Cisitid,@tablename,'Cformid', @audit_oldvalue, @audit_value,getdate(),@Action, coalesce(ModifiedBy,suser_name()), 'Cformid'
from inserted
--CreatedDate
select @audit_oldvalue = CreatedDate from deleted;
select @audit_value = CreatedDate from inserted;
insert into [dbo].[AuditTrailCTables]([TSid],[TableName],[TSField],[OldValue],[NewValue],[changedate],[Change_Action],[Change_user],[Columns_Updated])
select Cisitid,@tablename,'CreatedDate', @audit_oldvalue, @audit_value,getdate(),@Action, coalesce(ModifiedBy,suser_name()), 'CreatedDate'
from inserted
--CreatedBy
select @audit_oldvalue = CreatedBy from deleted;
select @audit_value = CreatedBy from inserted;
insert into [dbo].[AuditTrailCTables]([TSid],[TableName],[TSField],[OldValue],[NewValue],[changedate],[Change_Action],[Change_user],[Columns_Updated])
select Cisitid,@tablename,'CreatedBy', @audit_oldvalue, @audit_value,getdate(),@Action, coalesce(ModifiedBy,suser_name()), 'CreatedBy'
from inserted
END
答案 0 :(得分:0)
尝试使用UPDATE功能:
IF UPDATE(Cisitid)
insert into [dbo].[AuditTrailCTables]([TSid],[TableName],[TSField],[OldValue],
[NewValue],[changedate],[Change_Action],[Change_user],[Columns_Updated])
select Cisitid,@tablename,'Cisitid', @audit_oldvalue,
@audit_value,getdate(),@Action, coalesce(ModifiedBy,suser_name()), 'Cisitid'
from inserted
etc..