接下来综合实战一波,需求每次更新Test表,保存更新前的记录,将记录信息保存到更新日志表Test_Log中,最后将第一次更新的数据,更新回Test表中!
CREATE TABLE Test
(
id int,
name varchar(20)
)
CREATE TABLE Test_log
(
tid int identity,
id int,
name varchar(20),
createtime datetime
)
INSERT INTO TEST SELECT 1,'A'
INSERT INTO TEST SELECT 2,'B'
INSERT INTO TEST SELECT 3,'C'
CREATE trigger Test_Update_Triger
on Test
for update
AS
DECLARE @id int,@name varchar(20)
--将保存在deleted临时表中的数据查询出来
SELECT @id=id ,@name=name FROM deleted
--同步到Test_Log日志表
INSERT INTO Test_log SELECT @id,@name,getdate()
SELECT * FROM Test
UPDATE TEST SET NAME = 'A1' WHERE ID = 1;
UPDATE TEST SET NAME = 'A2' WHERE ID = 1;
UPDATE TEST SET NAME = 'A3' WHERE ID = 1;
UPDATE TEST SET NAME = 'B1' WHERE ID = 2;
UPDATE TEST SET NAME = 'B2' WHERE ID = 2;
UPDATE TEST SET NAME = 'C1' WHERE ID = 3;
UPDATE TEST SET NAME = 'C2' WHERE ID = 3;
UPDATE TEST SET NAME = 'C3' WHERE ID = 3;
UPDATE TEST SET NAME = 'C4' WHERE ID = 3;
SELECT * FROM TEST AS T
INNER JOIN TEST_LOG AS TL ON T.id = TL.id
每次更新都会触发触发器,保存我们的更新日志记录,满足我们对于参照完整性约束的需求,接下来我们通过SQL,让Test表中的数据,重新回到初始状态。
--STEP 1
SELECT MIN(createtime) as createtime FROM Test_log
GROUP BY id
--STEP 2
SELECT id,name,createtime FROM Test_log
WHERE createtime IN
(
SELECT MIN(createtime) as createtime FROM Test_log
GROUP BY id
)
--STEMP 3
UPDATE TEST SET NAME = T2.name FROM TEST AS T1
INNER JOIN
(
SELECT id,name,createtime FROM Test_log
WHERE createtime IN
(
SELECT MIN(createtime) as createtime FROM Test_log
GROUP BY id
)
)AS T2 ON T1.id = T2.id
SELECT * FROM TEST
总结一下:
以上就是关于触发器相关的知识,通过案例的深入,应该可以理解,并且掌握触发器的应用了!
喜欢的小伙伴可以关注我,一起交流学习!我是IT鸟叔,一位喜欢写程序、钓鱼、喝茶、玩游戏的中年大叔!