服务器之家

服务器之家 > 正文

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

时间:2020-04-02 15:29     来源/作者:whsnow

1. 插入数据前判断数据是否存在

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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. 删除表中数据时需要先删除外键表的数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

 

相关文章

热门资讯

沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情 2019-06-22
返回顶部