简单的触发器

定义: 何为触发器?在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。 
常见的触发器有三种:分别应用于Insert , Update , Delete 事件。 

表一:news表

CREATE TABLE [dbo].[news](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [title] [nvarchar](50) NULL,
 [contents] [nvarchar](50) NULL

表二:newsdel记录被删除、被修改过的news信息

CREATE TABLE [dbo].[newsdel](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [newsID] [int] NULL,
 [title] [nvarchar](50) NULL,
 [contents] [nvarchar](50) NULL

触发器的基本语法:

create trigger newsdeleted         -----创建触发器,名称可以自己随便叫
On news                                     -----表名称,即操作的对象,可多个
for Delete                                   -----事件,一般为Insert , Update , Delete 事件,可多选
As 
insert into newsdel(newsID,title,contents)               ---------------要执行的sql
select ID,title,contents from Deleted                      

注意:inserted临时表,表示新插入的信息,也包括新加的和修改后的新信息;

           deleted临时表,表示被删除的信息,也包括被修改前的信息

 

1>把删除的news信息保存在newsdel表中,我们需要一个delete触发器:

create trigger newsdeleted 
On news 
for Delete 
As 
insert into newsdel(newsID,title,contents) 
select ID,title,contents from Deleted

2>把修改前的news信息保存在newsdel表中,我们需要一个update触发器:

create trigger newsupdated
On news 
for update 
 As 
insert into newsdel(newsID,title,contents) 
select ID,title,contents from Deleted

转载于:https://www.cnblogs.com/webapi/archive/2012/03/30/2425939.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值