SQL中触发器

什么是触发器

其是一种特殊的存储过程。一般的存储过程是通过存储过程名直接调用,而触发器主要是通过事件(增、删、改)进行触发而被执行的。其在表中数据发生变化时自动强制执行。
常见的触发器有两种:after(for)、instead of,用于insert、update、delete事件。

  • after(for) 表示执行代码后,执行触发器
  • instead of 表示执行代码前,用已经写好的触发器代替你的操作。

触发器语法:

create trigger 触发器的名字   on 操作表

  for|after         instead of

  update|insert|delete

  as

  SQL语句

触发器有两个特殊的表:插入表(instered表)和删除表(deleted表)。这两张是逻辑表也是虚表。有系统在内存中创建者两张表,不会存储在数据库中。而且两张表的都是只读的,只能读取数据而不能修改数据。这两张表的结果总是与被改触发器应用的表的结构相同。当触发器完成工作后,这两张表就会被删除。Inserted表的数据是插入或是修改后的数据,而deleted表的数据是更新前的或是删除的数据。

这里写图片描述

Update数据的时候就是先删除表记录,然后增加一条记录。这样在inserted和deleted表就都有update后的数据记录了。注意的是:触发器本身就是一个事务,所以在触发器里面可以对修改数据进行一些特殊的检查。如果不满足可以利用事务回滚,撤销操作。

触发器示例

Example1
–禁止用户插入数据(实际上是先插入,然后立刻将其删除!)

  create trigger tr_insert on bank

  for –for表示执行之后的操作

  insert –即先执行了插入操作,同时在临时表中保存了插入记录

  as
  –执行完插入之后,在新生成的表中将刚刚插入的那条记录删除,
   –而此时得到的刚刚插入的记录的id是通过临时表 inserted得到的
  
  delete * from bank where cid=(select cid from inserted)

  生成上面的触发器后,当用户再输入insert语句后就见不到效果了!

  如:insert into bank values(‘0004’,10000),是插入不进数据库的。

Example2

–删除谁就让谁的账户加上10元

  create trigger tr_dalete on bank

  instead of

  delete

  as

  update bank balance=balance+10 where cid=(select cid from deleted)

  生成这个触发器之后,当用户输入delete语句后,对应的那个id不但没有被删除掉,而且他的账户增加了10元

  如:delete from bank where cid=’0002’,执行完这句话后,编号为0002的账户会增加10元

细节讲解

创建触发器

语法

create trigger tgr_name
on table_name
with encrypion –加密触发器
for update…
as
Transact-SQL

# 创建insert类型触发器

–创建insert插入类型触发器
if (object_id(‘tgr_classes_insert’, ‘tr’) is not null)
drop trigger tgr_classes_insert
go
create trigger tgr_classes_insert
on classes
for insert –插入触发
as
–定义变量
declare @id int, @name varchar(20), @temp int;
–在inserted表中查询已经插入记录信息
select @id = id, @name = name from inserted;
set @name = @name + convert(varchar, @id);
set @temp = @id / 2;
insert into student values(@name, 18 + @id, @temp, @id);
print ‘添加学生成功!’;
go
–插入数据
insert into classes values(‘5班’, getDate());
–查询数据
select * from classes;
select * from student order by id;
insert触发器,会在inserted表中添加一条刚插入的记录。

# 创建delete类型触发器

–delete删除类型触发器
if (object_id(‘tgr_classes_delete’, ‘TR’) is not null)
drop trigger tgr_classes_delete
go
create trigger tgr_classes_delete
on classes
for delete –删除触发
as
print ‘备份数据中……’;
if (object_id(‘classesBackup’, ‘U’) is not null)
–存在classesBackup,直接插入数据
insert into classesBackup select name, createDate from deleted;
else
–不存在classesBackup创建再插入
select * into classesBackup from deleted;
print ‘备份数据成功!’;

go

–不显示影响行数
–set nocount on;
delete classes where name = ‘5班’;
–查询数据
select * from classes;
select * from classesBackup;
delete触发器会在删除数据的时候,将刚才删除的数据保存在deleted表中。

# 创建update类型触发器

–update更新类型触发器
if (object_id(‘tgr_classes_update’, ‘TR’) is not null)
drop trigger tgr_classes_update
go
create trigger tgr_classes_update
on classes
for update
as
declare @oldName varchar(20), @newName varchar(20);
–更新前的数据
select @oldName = name from deleted;
if (exists (select * from student where name like ‘%’+ @oldName + ‘%’))
begin
–更新后的数据
select @newName = name from inserted;
update student set name = replace(name, @oldName, @newName) where name like ‘%’+ @oldName + ‘%’;
print ‘级联修改数据成功!’;
end
else
print ‘无需修改student表!’;
go
–查询数据
select * from student order by id;
select * from classes;
update classes set name = ‘五班’ where name = ‘5班’;
update触发器会在更新数据后,将更新前的数据保存在deleted表中,更新后的数据保存在inserted表中。

# update更新列级触发器

if (object_id(‘tgr_classes_update_column’, ‘TR’) is not null)
drop trigger tgr_classes_update_column
go
create trigger tgr_classes_update_column
on classes
for update
as
–列级触发器:是否更新了班级创建时间
if (update(createDate))
begin
raisError(‘系统提示:班级创建时间不能修改!’, 16, 11);
rollback tran;
end
go
–测试
select * from student order by id;
select * from classes;
update classes set createDate = getDate() where id = 3;
update classes set name = ‘四班’ where id = 7;
更新列级触发器可以用update是否判断更新列记录;

# instead of类型触发器

   instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身的内容。

   创建语法

create trigger tgr_name
on table_name
with encryption
instead of update…
as
T-SQL

  # 创建instead of触发器

if (object_id(‘tgr_classes_inteadOf’, ‘TR’) is not null)
drop trigger tgr_classes_inteadOf
go
create trigger tgr_classes_inteadOf
on classes
instead of delete/, update, insert/
as
declare @id int, @name varchar(20);
–查询被删除的信息,病赋值
select @id = id, @name = name from deleted;
print ‘id: ’ + convert(varchar, @id) + ‘, name: ’ + @name;
–先删除student的信息
delete student where cid = @id;
–再删除classes的信息
delete classes where id = @id;
print ‘删除[ id: ’ + convert(varchar, @id) + ‘, name: ’ + @name + ’ ] 的信息成功!’;
go
–test
select * from student order by id;
select * from classes;
delete classes where id = 7;

  # 显示自定义消息raiserror

if (object_id(‘tgr_message’, ‘TR’) is not null)
drop trigger tgr_message
go
create trigger tgr_message
on student
after insert, update
as raisError(‘tgr_message触发器被触发’, 16, 10);
go
–test
insert into student values(‘lily’, 22, 1, 7);
update student set sex = 0 where name = ‘lucy’;
select * from student order by id;

# 修改触发器

alter trigger tgr_message
on student
after delete
as raisError(‘tgr_message触发器被触发’, 16, 10);
go
–test
delete from student where name = ‘lucy’;

# 启用、禁用触发器

–禁用触发器
disable trigger tgr_message on student;
–启用触发器
enable trigger tgr_message on student;

# 查询创建的触发器信息

–查询已存在的触发器
select * from sys.triggers;
select * from sys.objects where type = ‘TR’;

–查看触发器触发事件
select te.* from sys.trigger_events te join sys.triggers t
on t.object_id = te.object_id
where t.parent_class = 0 and t.name = ‘tgr_valid_data’;

–查看创建触发器语句
exec sp_helptext ‘tgr_message’;

# 示例,验证插入数据

if ((object_id(‘tgr_valid_data’, ‘TR’) is not null))
drop trigger tgr_valid_data
go
create trigger tgr_valid_data
on student
after insert
as
declare @age int,
@name varchar(20);
select @name = s.name, @age = s.age from inserted s;
if (@age < 18)
begin
raisError(‘插入新数据的age有问题’, 16, 1);
rollback tran;
end
go
–test
insert into student values(‘forest’, 2, 0, 7);
insert into student values(‘forest’, 22, 0, 7);
select * from student order by id;

# 示例,操作日志

if (object_id(‘log’, ‘U’) is not null)
drop table log
go
create table log(
id int identity(1, 1) primary key,
action varchar(20),
createDate datetime default getDate()
)
go
if (exists (select * from sys.objects where name = ‘tgr_student_log’))
drop trigger tgr_student_log
go
create trigger tgr_student_log
on student
after insert, update, delete
as
if ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))
begin
insert into log(action) values(‘updated’);
end
else if (exists (select 1 from inserted) and not exists (select 1 from deleted))
begin
insert into log(action) values(‘inserted’);
end
else if (not exists (select 1 from inserted) and exists (select 1 from deleted))
begin
insert into log(action) values(‘deleted’);
end
go
–test
insert into student values(‘king’, 22, 1, 7);
update student set sex = 0 where name = ‘king’;
delete student where name = ‘king’;
select * from log;
select * from student order by id;

参与评论 您还未登录,请先 登录 后发表或查看评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

dongdongdongJL

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值