简体   繁体   中英

SQL Server 2012 trigger: Auditing. How to see previous value of a row without shadow table

I am trying to create an auditing table. I have a table called person.address in the AdventureWorks 2012 database.

I am using a trigger to capture changes to the table, the only problem is I do not know if it is possible to use a trigger to capture a row BEFORE it is edited. I am trying to save resources and overheads so trying to not use a shadow table. I know there is no "Before Insert" trigger. But is there any way to capture the information contained in a row, and when someone does an insert or update, this row can be written to my audit.table before the insert is completed?

Thank you.

Given a simplistic table with two rows:

CREATE TABLE dbo.foo(a INT PRIMARY KEY);

INSERT dbo.foo(a) VALUES(1),(2);

Then an update trigger simply to demonstrate:

CREATE TRIGGER dbo.trfoo ON dbo.foo FOR UPDATE
AS
BEGIN
  SET NOCOUNT ON;

  SELECT a FROM inserted;

  SELECT a FROM deleted;
END
GO

The result of an action, such as:

UPDATE dbo.foo SET a += 1;

Results in:

a    -- this is the *new* version of these rows
----
3
2

a    -- this is the *old* version of these rows
----
2
1

Also, there is an INSTEAD OF INSERT trigger, which allows you to perform actions before the insert (they're not called BEFORE triggers because you still have to perform the insert yourself). More info here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM