2010-07-05 34 views
28

我需要在SQL Server 2008中创建触发器,这些触发器将一些值更改为Log表的行从一行中插入!触发器插入旧值 - 已更新的值

例如,如果我有表雇员有列ID,名称,密码,我更新此表并插入新的值的列名称,比我需要插入表中的更新后,在表日志中的员工的值。

我该怎么做?谢谢!

+1

你的问题不是很清楚,你可以改换并可能展开。如果你能提供一个你想要的例子,它会有所帮助。 – 2010-07-05 18:01:23

+0

例如我有这样的价值,如 id 3; 名称Jon; 密码Jon; 现在我更新表Employees并更改名称Jon到Mark,在我更新之前我需要在日志表中插入值3,Jon,Jon。 – user383875 2010-07-05 18:08:18

回答

30

下面是一个例子更新触发器:

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 
72

在您的触发器中,您有两个可用的伪表,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表中的旧值,从Inserted表中的新价值,和你的一切存储在LogTable

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-----.'