首页 > 资讯列表 > 编程/数据库 >> 数据库操作教程

SqlServer实现类似Oracle的before触发器示例

数据库操作教程 2022-09-23 17:35:39 转载来源: 网络整理/侵权必删

1.插入数据前判断数据是否存在SETANSI_NULLSONGOSETQUOTED_IDENTIFIERONGO--=============================================--Author:<Author,,Name>--Createdate:<CreateDate,,>--Description:<Description,,>--=============================================alterTRIGGERCategoryExistTriggerONProductCategoryinsteadofinsertASdeclare@categoryNamevarchar(50);BEGIN--SETNOCOUNTONaddedtopreventextraresultsetsfrom--interferingwithSELECTstatements

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

标签: SqlServer 实现 类似 Oracle before 触发器 示例


声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!

站长搜索

http://www.adminso.com

Copyright @ 2007~2024 All Rights Reserved.

Powered By 站长搜索

打开手机扫描上面的二维码打开手机版


使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

站长搜索目录系统技术支持