sqlserver2000中触发器小实例!

--insert 触发器

create trigger tri_infoDetails_i on info_details
after insert
as
    declare @id int
begin
    --delete from info_details where id=
    select @id=id from inserted;
    insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG)
    select type,title,content,getdate(),1 from info_details where id=@id;
    --update info_details_index set content=content
end;

 

-- update触发器

--select top 0 type,title,content,getdate() as post_time,1  as flag  into info_details_index from info_details;
create trigger tri_infoDetails_u on info_details
after update
as
    declare @id int
begin
    if exists(select 1 from inserted)
         if exists(select 1 from deleted)
         begin
        select @id=id from inserted;
        insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG)select type,title,content,getdate(),-1 from info_details where id=@id;
        insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG)select type,title,content,getdate(),1 from info_details where id=@id;
         end
            
    --update info_details_index set content=content
end


--delete触发器

create trigger tri_infoDetails_d on info_details
after delete
as
    declare @id int
begin
   
         if exists(select 1 from deleted)
         begin
         
        insert into info_details_index(TYPE,TITLE, POST_TIME,FLAG)
        select type,title, getdate(),-1 from deleted info_details ;
         end
            
     
end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
定义: 何为触发器?在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。 常见的触发器有三种:分别应用于Insert , Update , Delete 事件。 我为什么要使用触发器?比如,这么两个表: Create Table Student( --学生表 StudentID int primary key, --学号 .... ) Create Table BorrowRecord( -学生借书记录表 BorrowRecord int identity(1,1), --流水号 StudentID int , --学号 BorrowDate datetime, --借出时间 ReturnDAte Datetime, --归还时间 ... ) 用到的功能有: 1.如果我更改了学生的学号,我希望他的借书记录仍然与这个学生相关(也就是同时更改借书记录表的学号); 2.如果该学生已经毕业,我希望删除他的学号的同时,也删除它的借书记录。 这时候可以用到触发器。对于1,创建一个Update触发器: Create Trigger truStudent On Student --在Student表创建触发器 for Update --为什么事件触发 As --事件触发后所要做的事情 if Update(StudentID) begin Update BorrowRecord Set StudentID=i.StudentID From BorrowRecord br , Deleted d ,Inserted i --Deleted和Inserted临时表 Where br.StudentID=d.StudentID end 理解触发器里面的两个临时的表:Deleted , Inserted 。注意Deleted 与Inserted分别表示触发事件的表“旧的一条记录”和“新的一条记录”。 一个Update 的过程可以看作为:生成新的记录到Inserted表,复制旧的记录到Deleted表,然后删除Student记录并写入新纪录。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值