据我所知,审计表是某种跟踪表(即捕获基表中的变化)
INSERT / UPDATE操作如何使用旧值和新值?不知道怎么编码呢
我需要编写AddressLine1 FROM Person.Address
的旧值和新值这就是我所拥有的一切:
USE AdventureWorks2012;
GO
-- AL1 is AddressLine1
-- also what about primary key???
CREATE TABLE AuditTable
(
AL1Old nvarchar(60) not null,
AL1New nvarchar(60) not null,
);
GO
-- should I update AuditTable there?
-- I don't know how to insert Old and New value by trigger...
CREATE TRIGGER triggy
ON Person.Address
AFTER INSERT, UPDATE
AS
-- ???
GO
答案 0 :(得分:1)
如果您想在触发器中插入旧数据和新数据,那么仅在UPDATE
触发器中工作 - INSERT
触发器没有显然,任何“旧的”数据。
基本上,您需要从Deleted
伪表中获取旧数据,并从Inserted
伪表中获取新数据。
另外:请注意,每个语句都会调用一次触发器,两个伪表都可以(并且会!)包含多行 - 也可以相应地对触发器进行编程。
要处理Addressline1
列 - 尝试这样的事情(是的,我还建议包含主键以识别此数据的行!)
-- AL1 is AddressLine1
-- also what about primary key???
CREATE TABLE AuditTable
(
PrimaryKey INT NOT NULL,
AL1Old nvarchar(60) not null,
AL1New nvarchar(60) not null,
);
GO
-- I don't know how to insert Old and New value by trigger...
CREATE TRIGGER addressUpdateTrigger
ON Person.Address
AFTER UPDATE
AS
INSERT INTO dbo.AuditTable(PrimaryKey, AL1Old, AL1New)
SELECT
Inserted.AddressID, -- primary key
Deleted.AddressLine1, -- old data
Inserted.AddressLine1 -- new data
FROM
Inserted
INNER JOIN
Deleted on Inserted.AddressID = Deleted.AddressID
GO