时间:2021-07-01 10:21:17 帮助过:24人阅读
定义:
在修改指定表值的数据时执行的 存储过程. 不同的是 : 执行存储过程要使用EXEC语句来调用,而触发器的执行不需要使用EXEC语句来调用.
作用:
实现由主键和外键所不能保证的复制的参照完整性和数据的一致性
他能够对数据库中的相关表进行级联修改
提供比 CHECK约束 更复杂的数据完整性,并自定义错误信息。
分类:
数据操作语言触发器 DML
数据库操作语言 : update,Delete
数据定义语言触发器 DDL
记录数据库更改事件
Create trigger employee_delete
on Department
After Delete
AS
Begin
Declary @x char(10)
Select @x = DepartmentName --变量来自数据库,用from
From Department
if (@x = ‘人事部‘) --没有就用变量
Begin
print ‘无法删除‘
RollBack --撤销都是RollBack
End
End
--执行
Delete From Department Where Sname = ‘人事部‘
Create trigger employee_delete
on Employee
After Delete
AS
Begin
Declare @Dp varchar(50)
Select @Dp = DepartmentName
From Department D1, Deleted D2
Where D1.DepartmentID = D2.DepartmentID
If(@Dp = ‘人事部‘)
Begin
print ‘无法删除‘
RollBack
End
End
Create trigger employee_update
on Stu_info
After Update
AS
Begin
Declare @StuCount Int
Select @StuCount = Count(*)
From stu_info
Update Stu_sum
Set number = @StuCount
Select S_id As 更新前学生编号, S_name As 更新前学生姓名
From Deleted
Select S_id As 更新后学生编号, S_name As 更新后学生姓名
From Inserted
End
--执行
Update Stu_info
Set S_name = ‘张三‘
Where S_id = 1
Create trigger employee_delete
on Employee
Instead of Delete
AS
Begin
Declare @Dp varchar(50)
Select @Dp = DepartmentName
From Department
If(@Dp = ‘人事部‘)
Begin
print ‘无法删除‘
End
End
Create Trigger Insert_Forbidden
On Stu_Sum
After Insert
AS
Begin
Raiserror(‘不允许直接向该表插入记录, 操作被禁止‘, 1, 1)
RollBack Transaction
End
服务器 - > 属性 -> 杂项 -> 允许触发器激发其他触发器 -> true
数据库 -> 属性 -> 选项 -> 杂项 -> 递归触发器已启用 -> true
SQL语句(二十一)—— 触发器(DML触发器)
标签:lin back containe begin 存储过程 container strong tran 触发器