图书管理系统触发器讲解学习.docx
《图书管理系统触发器讲解学习.docx》由会员分享,可在线阅读,更多相关《图书管理系统触发器讲解学习.docx(8页珍藏版)》请在冰豆网上搜索。
![图书管理系统触发器讲解学习.docx](https://file1.bdocx.com/fileroot1/2022-10/19/714d0936-9470-4a01-88fc-df3b7f653821/714d0936-9470-4a01-88fc-df3b7f6538211.gif)
图书管理系统触发器讲解学习
触发器
触发器相关的概念
触发器是一种特殊的存储过程,触发器基于表建立,可视作表的一部分。
触发器实在数据发生更新时,自动触发。
用于实现强制业务规则和数据完整性。
触发器是用户对某一表中数据进行update、insert和delete操作时被自动触发的一段程序。
触发器有助于强制引用完整性,以便在更新表中行时,保留表之间也定义的关系。
1、创建触发器:
为书库表创建一个触发器,用来禁止修改书库号:
不能修改书库号:
createtriggerupdate_Lib_tr
onLibrary
afterupdate
as
ifupdate(LibraryNo)
begin
raiserror('不能修改书库号',16,2)
rollback
end
触发器验证:
Select*fromLibrary
UpdateLibrarysetLibraryNo='4'whereLibraryNo='1'
Select*fromLibrary
(外键约束)
2、创建触发器:
为管理员表创建一个触发器,用来禁止修改管理员编号:
不能修改管理员编号:
createtriggerupdate_Wor_tr
onWorker
afterupdate
as
ifupdate(WorkerID)
begin
raiserror('不能修改管理员编号',16,2)
rollback
end
Select*fromWorker
UpdateWorkersetWorkerID='103'whereWorkerID='104'
Select*fromWorker
3、创建触发器:
为图书表创建一个触发器,用来禁止修改图书编号:
不能修改图书编号:
createtriggerupdate_Boo_tr
onBook
afterupdate
as
ifupdate(BookID)
begin
raiserror('不能修改图书编号',16,2)
rollback
end
触发器验证:
Select*fromBook
UpdateBooksetBookID='1014'whereBookID='1016'
Select*fromBook
4、创建触发器:
为学生表创建一个触发器,用来禁止修改学号:
不能修改学号:
createtriggerupdate_Stu_tr
onStudent
afterupdate
as
ifupdate(StudentID)
begin
raiserror('不能修改学号',16,2)
rollback
end
触发器验证:
Select*fromStudent
UpdateStudentsetStudentID='1014'whereStudentID='1016'
Select*fromStudent
5、创建触发器:
为借阅表创建一个触发器,用来禁止删除“未还”的记录:
不能删除“未还”的记录:
createtriggerdelete_Bor_tr
onBorrow
insteadofdelete
as
ifexists(select*fromBorrowwhereState='未还')
begin
raiserror('不能删除“未还”的记录',16,2)
rollback
end
验证:
select*fromBorrow
deletefromBorrowwhereBorrowNo='3'
select*fromBorrow
6、创建触发器:
为借阅表创建一个触发器,当借阅表中数据被删除时,学生表中的相关数据也会被删除:
当Borrow表中数据被删除时,Student表中的相关数据也会被删除:
createtriggerdelete_Bor_Stu_tr
onBorrow
afterdelete
as
print'当删除借阅表中记录时,学生表中的相关数据也被删除'
deletefromStudent
whereStudentIDin(selectStudentIDfromdeleted)
触发器验证:
select*fromStudent
deletefromBorrowwhereStudentID='2015012'
select*fromStudent
7、创建触发器:
为书籍表创建一个触发器,当书籍表中数据被删除时,删除的数据备份到另外一张表中:
备份:
select*intoBook_backupfromBookwhere1=2
createtriggerBook_delete_backup_tr
onBook
afterdelete
as
ifexists(select*fromdeleted)
begin
insertintoBook_backupselect*fromdeleted
print'删除数据在Book_backup中做备份'
end
触发器验证:
deletefromBookwhereBookID='1011'
select*fromBook_backup
(外键约束)