触发器(trigger)是SQL server 提供给程序员和数据分析员来保证数据完整性的一种方法,它是与表事件相关的特殊的存储过程,它的执行不是由程序调用,也不是手工启动,而是由事件来触发,当对一个表进行操作( insert,delete, update)时就会激活它执行。触发器经常用于加强数据的完整性约束和业务规则等。
某张表插入数据需要同时写到另外一张表,下面介绍下如何用sqlserver触发器来实现。
这里跟Oracle数据库的create table xx as select XX不一样
select * into LJPL_XX_LJYHXX_MID from LJPL_XX_LJYHXX WHERE 1=2; select * into LJPL_XX_LJJHXX_MID from LJPL_XX_LJJHXX WHERE 1=2; select * into LJPL_XX_RQFH_MID from LJPL_XX_RQFH WHERE 1=2;
这里要注意我分别用了AFTER和instead of两个用法。
且sqlserver的INSERTED代表插入后的数据,这个要比Oracle实用很多,因为Oracle触发器不能直接写全部字段,只能一个一个字段:new.字段名这种方式,麻烦很多。
--判断触发器是否存在 if exists(select * from sysobjects where name='trg_ljjhxx') drop trigger trg_ljjhxx; go CREATE TRIGGER dbo.trg_ljjhxx ON dbo.LJPL_XX_LJJHXX AFTER INSERT AS BEGIN INSERT INTO LJPL_XX_LJJHXX_MID SELECT * FROM INSERTED END go --判断触发器是否存在 IF EXISTS ( SELECT * FROM sysobjects WHERE NAME = 'trg_rqfh' ) DROP TRIGGER trg_rqfh; go CREATE TRIGGER dbo.trg_rqfh ON dbo.LJPL_XX_RQFH instead of INSERT AS BEGIN INSERT INTO LJPL_XX_RQFH_MID SELECT * FROM INSERTED END go --判断触发器是否存在 IF EXISTS ( SELECT * FROM sysobjects WHERE NAME = 'trg_ljyhxx' ) DROP TRIGGER trg_ljyhxx; go CREATE TRIGGER dbo.trg_ljyhxx ON dbo.LJPL_XX_LJYHXX instead of INSERT AS BEGIN INSERT INTO LJPL_XX_LJYHXX_MID SELECT * FROM INSERTED END go
测试成功
INSERT INTO LJPL_XX_RQFH ( [FID], .... ) VALUES ( N'00061017-16EE-4CED-806A-3EF8F3D47466', N'M810550000', N'黄伟波', ... ); SELECT * FROM LJPL_XX_RQFH WHERE FID=N'00061017-16EE-4CED-806A-3EF8F3D47466'