码迷,mamicode.com
首页 > 数据库 > 详细

16、SQL基础整理(触发器.方便备份)

时间:2014-12-15 17:01:22      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   strong   

触发器(方便备份)

本质上还是一个存储过程,只不过不是通过exec来调用执行,而是通过增删改数据库的操作来执行(可以操作视图)

 bubuko.com,布布扣

bubuko.com,布布扣

 

全部禁用触发器

alter table teacher disable trigger all

全部开启触发器

alter table teacher enable trigger all

create trigger TR_student_delete--默认触发器名

on student --在哪个表上操作

instead of delete --为了对表做什么而建的,‘for’是在执行完外部语句之后用,‘instead of’是直接将要执行的语句替换为执行as里面的语句

as

    delete from score where sno =108

    delete from student where Sno = 108

go

delete from student where Sno = 108

 

select *from student

bubuko.com,布布扣108行被删掉

 

alter trigger TR_student_delete--默认触发器名

on student --在哪个表上操作

for delete

as

    insert into student values(108,‘曾鹏‘,‘男‘,1905-05-22,95033)

go

delete from student where Sno = 108

 

select *from student

bubuko.com,布布扣*曾华变为了曾鹏

 

动态触发

create trigger dongtaichufa

on teacher

instead of delete

as

begin

    declare @tno varchar(20)

    set @tno = (select tno from deleted)—-选择执行语句中的tno所在@tno

    update teacher set tname=‘张三‘where tno = @tno

end

go

delete from teacher where Tno=‘831‘

deleted存储删除后的信息,inserted存放更改后的信息。

执行delete语句时的tno=触发器里面的tno,而不是@tno

 bubuko.com,布布扣

create trigger TR_teacher_insert

on teacher

for insert

as

begin

    declare @tno varchar(20)

    set @tno=(select tno from inserted)

    ---delete from teacher where tno=@tno

    declare @sex varchar(10)

    set @sex =(select tsex from teacher where tno=@tno)

    if(@sex=‘男‘)

    update teacher set tsex=‘女‘where tno =@tno

    else

    update teacher set tsex=‘男‘where tno =@tno

end

go

insert into teacher values (800,‘王五‘,‘男‘,1990-09-09,‘教授‘,‘计算机系‘)

 bubuko.com,布布扣

16、SQL基础整理(触发器.方便备份)

标签:style   blog   http   io   ar   color   sp   for   strong   

原文地址:http://www.cnblogs.com/wleaves/p/4165147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!