当前位置:Gxlcms > 数据库问题 > SQL Server 触发器

SQL Server 触发器

时间:2021-07-01 10:21:17 帮助过:2人阅读

触发器,他与存储过程很相似,可以说触发器是一种特殊类型的存储过程,但触发器主要是通过事件进行触发被自动调用执行的,而存储过程可以通过存储过程的名称被调用。

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 触发器

标签:

人气教程排行