Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

SQL Server 2008 - Beim Einfügen/Aktualisieren-Trigger, der Werte in eine andere Tabelle kopiert?

Ganz einfach...

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