SqlServer实现类似Oracle的before触发器示例
1. 插入数据前判断数据是否存在
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= alter TRIGGER CategoryExistTrigger ON ProductCategory instead of insert AS declare @categoryName varchar(50); BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for trigger here select @categoryName = CategoryName from inserted; if exists(select * from ProductCategory where CategoryName =@categoryName) begin print 'Category exists..' end; else begin insert into ProductCategory select * from inserted; end; END
2. 删除表中数据时需要先删除外键表的数据
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= alter TRIGGER DeleteOrderTrigger ON OrderHeader instead of delete AS declare @OrderId varchar(50); BEGIN SET NOCOUNT ON; select @OrderId = OrderId from deleted; delete from OrderLine where OrderId = @OrderId; END GO
相关推荐
maokaijiang 2020-02-13
oArvin 2020-01-03
sui 2020-01-05
昊 2020-06-16
daillo 2020-04-07
applex 2019-12-29
zhaojp0 2019-12-11
xzero 2019-12-08
talkingDB 2019-12-02
zjuwangleicn 2020-06-25
debugjoker 2020-06-17
sunnyxuebuhui 2020-06-14
hanshangzhi 2020-06-14
ncomoon 2020-06-14
hanshangzhi 2020-06-12
wudaokouer 2020-04-16
一昕之代码 2020-02-20
李轮清 2020-05-11
URML 2020-05-10