[英]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.