这里以实际例子对触发器的应用对触发器的理解与应用来得更实际
一.更新触发器(Update)
临时表:inserted表有数据(新数据) Deleted表有数据(旧数据)
实例说明:当表更新时,并检测到更新了交期与数量字段,并连表更新另外一张表的数据(交期与数量),同时对历史更新的数据进行备份
-- ======================================================= -- 触发器概述:更新 交期与数量 -- ======================================================== CREATE TRIGGER [dbo].[mktdelivery_update] ON [dbo].[mktdelivery] FOR UPDATE AS if (update(deldate) OR update(delqty)) BEGIN UPDATE aa SET aa.okdate = bb.deldate,aa.qty = bb.delqty FROM mkthtpsb aa INNER JOIN INSERTED bb ON aa.cno = bb.shipway AND aa.pdctno = bb.pdctno INSERT mkthtpsb_back(ID,cno,okdate,pdctno,qty,addr) SELECT ID,cno,deldate,pdctno,delqty,HOST_NAME() FROM Deleted END
二.插入触发器(Insert)
临时表:Inserted表有数据, Deleted表无数据
实例说明:当插入记录时,插入的数据会记录在Inserted表中,拿到订单类型是否时,并更新另外一个表的数据(交期与数量)
-- ========================================================= -- 触发器概述:插入 更新(交期与数量) NP单更新产地确认 -- ======================================================== ALTER TRIGGER [dbo].[mktdelivery_insert] ON [dbo].[mktdelivery] FOR INSERT AS DECLARE @isnewpdctno VARCHAR(10) DECLARE @cno VARCHAR(20) DECLARE @deldate DATETIME DECLARE @delqty INT SELECT @isnewpdctno = isnewpdctno,@cno = shipway,@deldate=deldate,@delqty=delqty FROM INSERTED IF (@isnewpdctno IN ('否') ) BEGIN UPDATE aa SET aa.FactoryConfirmDate = GETDATE(),aa.okdate = @deldate,aa.qty = @delqty FROM mkthtpsb aa WHERE cno = @cno AND isnewpdctno IN ('否') END
三.删除触发器(Deleted)
临时表:Inserted表无数据,Deleted表有数据
实例说明:当删除记录时,删除的数据会记录在Deleted表中,在删除前对关键数据进行备份
-- ======================================================= -- 触发器概述:删除数据 对关键数据进行备份记录 -- ======================================================== ALTER TRIGGER [dbo].[mkthtpsb_del] on [fp_db].[dbo].[mkthtpsb] FOR DELETE AS INSERT mkthtpsb_back(ID,cno,getdate,okdate,pdctno,custpno,qty,addr) SELECT ID,cno,[getdate],okdate,pdctno,custpno,qty,HOST_NAME() FROM Deleted