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

2023年 4月 19日 31.0k 0

1. 插入数据前判断数据是否存在 SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- 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,,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

相关文章

Oracle如何使用授予和撤销权限的语法和示例
Awesome Project: 探索 MatrixOrigin 云原生分布式数据库
下载丨66页PDF,云和恩墨技术通讯(2024年7月刊)
社区版oceanbase安装
Oracle 导出CSV工具-sqluldr2
ETL数据集成丨快速将MySQL数据迁移至Doris数据库

发布评论