简体   繁体   English

SQL Server 2008-在插入/更新时触发将值复制到另一个表的触发器吗?

[英]SQL Server 2008 - On Insert/Update Trigger that copies values to another table?

I have these two tables: Tasks and TasksHistory, from the name you can guess that I want to create a history of everything that's been going on in Tasks. 我有两个表:Tasks和TasksHistory,从名称可以猜到我想创建Tasks中正在进行的所有操作的历史记录。 So, every new row inserted or updated needs to go into the history table, just ignoring when it's deleted, keeping the row safe in history. 因此,每个插入或更新的新行都需要进入历史记录表,而忽略其删除时间,从而使该行在历史记录中保持安全。 My idea is that history be an exact replica of the original table. 我的想法是,历史记录是原始表的精确副本

How can I achieve this? 我该如何实现?

Quite simple... 非常简单...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 INSERT到另一个表中的表和UPDATE外键(Sql Server 2008) - INSERT into table and UPDATE foreign key in another table (Sql Server 2008) SQL Server 2008更新表包含另一个表中的值 - SQL Server 2008 update table with values from another table 从SQL Server 2008中的另一个表插入值 - Insert values from another Table in sql server 2008 SQL Server:在插入触发器以更新另一个表之后 - SQL Server : After Insert Trigger for update another Table Sql Server触发器将值从新行插入另一个表 - Sql Server trigger insert values from new row into another table SQL:创建自动将一些值复制到另一个表中的触发器 - SQL: Create Trigger that automatically copies some values into another table 如何根据SQL Server 2008中另一个表中的值编写更新触发器来更新当前表? - How can I write an update trigger to update the current table based on a value in another table in SQL Server 2008? SQL 2008 Express(R2):创建UPDATE触发器以更新另一台服务器上的表吗? - SQL 2008 Express (R2): Creating an UPDATE trigger to update a table on another server? SQL Server 2008 R2-表上的更新触发器更新另一个表中的单个行/单元 - SQL Server 2008 R2 - Update Trigger on a table updates a single row/cell in another table 插入后更新另一个表的SQL触发器 - SQL Trigger after insert update another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM