sql >> Base de Datos >  >> RDS >> Sqlserver

SQL Server 2008:¿en el activador de inserción/actualización que copia valores en otra tabla?

Muy sencillo...

CREATE TRIGGER TRG_Tasks_UI ON Tasks FOR INSERT,UPDATE
AS
SET XACT_ABORT, NOCOUNT ON

--Ignore zero row updates, inserts
IF NOT EXISTS (SELECT * FROM INSERTED) RETURN;

BEGIN TRY
    INSERT TasksHistory
       (col1, col2, ...)
    SELECT
       I.*
    FROM
       INSERTED I
       LEFT JOIN
       DELETED D ON I.key = D.Key
    WHERE
       D.Key IS NULL --insert only
       OR -- need null handling here
       I.col1 <> D.col1 OR I.col2 <> D.col2 OR ...;
END TRY
BEGIN CATCH
   IF XACT_STATE() <> 0 ROLLBACK TRANSACTION
    RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
END CATCH
GO