触发器
步骤:打开选用的‘数据库’,然后打开‘可编程性’,就可以找到‘数据库触发器’。
是一种存储过程,只是不通过 exec 调用执行!
通过增删改语句来引发执行!
在有主外键关联时,可以把关联的信息都修改
(有主外键关联时,要先删除外键才可以删主键)
create table new
(code int ,
shu int)
go
insert into new values (1,1)
insert into new values (2,3)
insert into new values (3,4)
insert into new values (4,5)
insert into new values (5,6)
select *from new
drop table new
----------------------------------------------------
create trigger TR_new_Delete --创建并命名触发器
on new --作用于new 表
for delete--delete/insert/update --先执行删除语句,再进行插入语句
as
insert into new values (11,11)--占据删除数据的位置
insert into new values (3,4)--在新插入数据的位置
go –到此,触发器完成。
delete from new where code=3
--引发触发器语句,只能是增删改
select *from new
for/after 先运行go再运行as
--先go删除了code=3,再as添加了code=11,code=3
-- drop trigger TR_new_Delete
--------------------------------------------------
create trigger TR_new_Delete
on new
instead of delete
as
insert into new values (11,11)
go
delete from new where code=2
select * from new
--此时不执行删除语句,只执行插入语句!
instead of只运行as的语句
----------------------------------------------
alter trigger dongtaichufa
on teacher
instead of delete
as
begin
declare @Tno varchar(20)
set @Tno=(select Tno from deleted)
--deleted 表示虚拟表(go后面的delete 语句)
update teacher set Tname='递归'where Tno=@Tno
end
go
delete from teacher where Tno='856'
select *from teacher
---------------------------------------------
--触发器可以处理视图,(用途:1.删除数据时备份2.操作视图,即有主外键关联时)
create trigger inserttt
on teacher
for insert
as
declare @Tno varchar(19)
set @Tno=(select Tno from inserted)
update teacher set Tsex='男'where Tno=@Tno --修改表内容
go
insert into teacher values
('789','集合','女','1990-09-09','教授','生物系')
select *from teacher
----------------------------------------------
alter table teacher disable trigger all--(或触发器名字)禁用全部
alter table teacher enable trigger all--(或触发器名字)启用全部
#########################
事物:
就是把语句‘打包’执行,只要发生错误,全部执行失败!
begin tran --开始‘事务’
--一般对增删改使用‘事物’!查询一般不用’事物’
insert into student values ('910','王五','男','1999-09-09','95033')
if @@ERROR >0--一旦发生错误,执行下面的返回!
goto TranRollback
insert into course values ('3-999','语文','804')
if @@ERROR >0
goto TranRollback
insert into score values ('191','3-105',99)
if @@ERROR >0
begin
TranRollback: rollback tran --返回tran 开始!
end
else
begin
commit tran--确认提交tran 执行语句内容!
end