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,,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触发器示例。踏出一步又一步,又只能收回一步一步。成长,有些苦涩始终都要去尝。更多关于SqlServer如何实现类似Oracle的before触发器示例请关注haodaima.com其它相关文章!

标签: SqlServer