So as I understand, the audit tables are some kind of tracking tables (ie to capture changes in base table)
How INSERT / UPDATE op works with old and new values? Dunno how to code it
I need to write old and new values of AddressLine1 FROM Person.Address
That's all what I have:
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
If you want to insert the old and new data in a trigger, then that'll only work in an UPDATE
trigger - the INSERT
trigger doesn't have any "old" data, obviously.
Basically, you need to get the old data from the Deleted
pseudo table, and the new data from the Inserted
pseudo table.
Also: be aware that a trigger is called once per statement and both pseudo tables can (and will!) contain multiple rows -so program your trigger accordingly.
To handle the Addressline1
column - try something like this (and yes, I would also recommend to include the primary key to identify what row this data is for!)
-- 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