时间:2021-07-01 10:21:17 帮助过:3人阅读
# 创建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是否判断更新列记录;
SQL Server 触发器
标签: