我为审计编写了一个触发器。我正在尝试将数据写入名为audit.table的审计表。 每当请求插入时,我希望触发器在插入之后写入新值,并在插入之前写入行值。我希望将行中的数据写入xml并写入新表中的行。到目前为止,除了前一行值之外,插入没有写入“删除表”之前,我认为它可能是我的“更新,删除,选择”
这是我的SQL。
USE [AdventureWorks2012]
GO
/****** Object: Trigger [Person].[dPerson] Script Date: 09/01/2014 16:38:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--create audit table
-- Create trigger to populate HumanResources
ALTER TRIGGER [Person].[dPerson] ON [Person].[Address]
for UPDATE, DELETE, INSERT
AS
declare @AuditUser varchar(50),
@AuditDate datetime,
@AuditAction char(1),
@PrevValue XML,
@AuditTable varchar(50),
@AuditHost nvarchar(128),
@AuditTablePK int,
@AuditApp nvarchar(128),
@xml XML
select @AuditUser = SYSTEM_USER
select @AuditDate = getDate()
select @AuditTable = 'Person.Address'
select @AuditHost = HOST_NAME()
select @AuditApp = APP_NAME()
select @AuditTablePK = IDENT_CURRENT('Person.Address')
SET NOCOUNT On;
set new value
SET @xml =
(
SELECT [AddressID], [AddressLine1], [AddressLine2], [City], [StateProvinceID], [SpatialLocation].ToString(), [PostalCode], [rowguid], [ModifiedDate]
FROM INSERTED
FOR XML PATH('Inserted')
);
--set old row value
-- --set old row value
SET @PrevValue =
(
SELECT [AddressID], [AddressLine1], [AddressLine2], [City], [StateProvinceID], [SpatialLocation].ToString(), [PostalCode], [rowguid], [ModifiedDate]
FROM deleted
FOR XML PATH('Deleted')
);
if exists (select * from deleted)
if exists (select * from inserted)
begin
select @AuditAction = 'U'
-- select @NewValue = select NewValue from inserted
end
else
begin
select @AuditAction = 'D'
--select @NewValue = NULL
end
--else
begin
insert into AdventureWorks2012.HumanResources.Audit.Table(PrevValue) values (@PrevValue)
INSERT INTO AdventureWorks2012.HumanResources.Audit.Table
(AuditUser, AuditAction, AuditDate, AuditTable, AuditHost, NewValue, PrevValue, AuditTablePK, AuditApp)
values (SYSTEM_USER, 'I', getDate(), 'Person.Address', HOST_NAME(), @xml, @PrevValue, IDENT_CURRENT('Person.Address'), APP_NAME() )
end
Insert into HumanResources.Audit.Table (AuditUser, AuditDate, AuditAction, NewValue, PrevValue, AuditTable, AuditTablePK, AuditHost, AuditApp)
select @AuditUser, @AuditDate, @AuditAction, @xml, @PrevValue, @AuditTable, @AuditTablePK, @AuditHost, @AuditApp
from deleted
--end
audit.table上的prevValue只返回一个空值。删除的表值不能被触发?
谢谢