触发器插入旧值 - 已更新的值

时间:2010-07-05 17:50:54

标签: sql tsql sql-server-2008

我需要在SQL Server 2008中创建触发器,该触发器从一行中插入所有值,其中某些值已更改为Log表!

例如,如果我的表Employees具有列id,名称,密码,并且我更新此表并为列名插入新值,那么我需要在表Log中更新表中Employees之后的值。 / p>

我怎么能这样做?谢谢!

5 个答案:

答案 0 :(得分:87)

在触发器中,您有两个可用的伪表,InsertedDeleted,其中包含这些值。

在UPDATE的情况下,Deleted表将包含旧值,而Inserted表包含新值。

因此,如果您想在触发器中记录ID, OldValue, NewValue,则需要编写如下内容:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS 
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

基本上,您加入InsertedDeleted伪表,抓取ID(在两种情况下都是相同的,我认为),来自Deleted的旧值table,Inserted表中的新值,并将所有内容存储在LogTable

答案 1 :(得分:37)

以下是更新触发器的示例:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

这将打印:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

答案 2 :(得分:1)

在SQL Server 2008中,您可以使用Change Data Capture。有关如何在桌面上进行设置的详细信息,请访问http://msdn.microsoft.com/en-us/library/cc627369.aspx

答案 3 :(得分:0)

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

答案 4 :(得分:-2)

ALTER在Employee FOR UPDATE上触发ETU 如 插入Log(EmployeeId,LogDate,OldName) 选择EmployeeId,getdate(),name 从删除 去