首页 > 数据库技术 > 详细

SQL Server 触发器

时间:2015-08-01 01:06:45      阅读:334      评论:0      收藏:0      [点我收藏+]

      在学习牛腩的时候我第一次正式在SQL Server 实现了触发器,他与存储过程很相似,可以说触发器是一种特殊类型的存储过程,但触发器主要是通过事件进行触发被自动调用执行的,而存储过程可以通过存储过程的名称被调用。

1,创建触发器

<span style="font-size:18px;">-- ================================================
-- Template generated from Template Explorer using:
-- Create Trigger (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- See additional Create Trigger templates for more
-- examples of different Trigger statements.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER trigCategoryDelete
   ON  category
   instead of DELETE
AS 
BEGIN
	declare @caID int
	select @caID=id from deleted
	--删除评论
	delete comment where newsId in (select newsId from news where caID =@caID )
	--删除新闻
	delete news where caID=@caID 
	--删除新闻类别
	delete category where id=@caID 
	
END
GO
</span>

2,修改触发器

<span style="font-size:18px;">USE [newssystem]

GO

/****** Object:  Trigger [dbo].[trigCategoryDelete]    Script Date: 06/10/2015 16:48:45 ******/

SET ANSI_NULLS ON

GO

SETQUOTED_IDENTIFIER ON

GO

--=============================================

--Author:                tsj

-- Create date: 2015年6月9日16:40:00

--Description:        删除类别触发器

--=============================================

ALTER TRIGGER[dbo].[trigCategoryDelete]

   ON [dbo].[category]

   AFTER delete

AS 

BEGIN

--select* from deleted

declare @caId int ---定义变量

select @caId=id from deleted -----从 deleted中取出id

--删除评论

deletecomment where newsId=(select newsId from news where caID=@caId)

 

--删除新闻

deletenews where caID=@caID

 

--删除类别

deletecategory where id=@caID

 

 

END
</span>


 

3,删除触发器:

<span style="font-size:18px;">drop trigger trigger_name 
</span>


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

SQL Server 触发器

原文:http://blog.csdn.net/tsj11514oo/article/details/47173801

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!