Trigger insertar valores antiguos-valores que se actualizaron


Necesito crear un disparador en SQL Server 2008 que se ha insertado todos los valores de una fila en la que se cambió algún valor en la tabla de registro!

Por ejemplo, si tengo Empleados de la tabla que tienen id de columna , nombre, contraseña, y actualizo esta tabla e inserto un nuevo valor para el nombre de la columna, entonces necesito insertar valores que estaban en Empleados de la tabla después de la actualización en el registro de la tabla.

¿Cómo puedo hacer esto? ¡Gracias!

Author: user383875, 2010-07-05

5 answers

Aquí hay un ejemplo de activación de actualización:

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

Esto se imprimirá:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid
 34
Author: Andomar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-05 18:12:47

En su trigger, tiene dos pseudo-tablas disponibles, Inserted y Deleted, que contienen esos valores.

En el caso de una ACTUALIZACIÓN, la tabla Deleted contendrá los valores antiguos, mientras que la tabla Inserted contendrá los nuevos valores.

Así que si quieres registrar el ID, OldValue, NewValue en tu trigger, necesitas escribir algo como:

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

Básicamente, se unen las pseudo-tablas Inserted y Deleted, agarrar el ID (que es el mismo, supongo, en ambos casos), el valor antiguo de la Deleted tabla, el nuevo valor de la tabla Inserted, y se almacena todo en el LogTable

 78
Author: marc_s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-05 18:12:36

En SQL Server 2008 puede usar la Captura de Datos de Cambio para esto. Los detalles de cómo configurarlo en una tabla están aquí http://msdn.microsoft.com/en-us/library/cc627369.aspx

 1
Author: Martin Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-06 06:46:53
    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-----.'
 0
Author: Masum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 09:53:08

ALTER trigger ETU en Empleado PARA ACTUALIZACIÓN COMO insertar en el registro (EmployeeID, LogDate, OldName) select EmployeeID, getdate (), name de borrado go

 -2
Author: user9658686,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 04:24:30