微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐