加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SqlServer 实现类似Oracle 的before触发器

发布时间:2020-12-12 13:14:07 所属栏目:MsSql教程 来源:网络整理
导读:1. 插入数据前判断数据是否存在 SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author:Author,Name-- Create date: Create Date,-- Description:Description,-- =====================================

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,>
-- =============================================
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读