目录
前言
原先写过一篇类似的,不过是基于Mysql:添加链接描述
对应Sql Server的补充知识点:详细配置SQL Server的链接服务器(图文操作Mysql数据库)
1. 基本知识
基本知识其实差不多,先从CRUD开始
触发器的类型:
- DML触发器:在对表进行插入、更新或删除操作时触发
AFTER触发器:在操作完成后执行
INSTEAD OF触发器:代替操作执行,操作本身不会发生 - DDL触发器:在对数据库对象进行创建、修改或删除时触发
- LOGON触发器:在用户登录到数据库时触发
触发器的作用:
- 数据验证:在数据修改前或后执行额外的验证逻辑
- 审计记录:记录数据的变更历史
- 自动计算:基于表中的数据自动计算其他值
2. Demo
创建触发器:
CREATE TRIGGER trigger_name
ON table_name
[AFTER | INSTEAD OF] {INSERT | UPDATE | DELETE}
AS
BEGIN
-- 触发器逻辑
END;
增加触发器:
CREATE TRIGGER trg_AfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
INSERT INTO AuditLog (Action, LogDate, EmployeeID)
SELECT 'INSERT', GETDATE(), EmployeeID
FROM inserted;
END;
更新触发器:
CREATE TRIGGER trg_InsteadOfUpdate
ON Employees
INSTEAD OF UPDATE
AS
BEGIN
-- 执行自定义的更新逻辑
UPDATE Employees
SET Name = inserted.Name
FROM inserted
WHERE Employees.EmployeeID = inserted.EmployeeID;
END;
查看触发器:
SELECT *
FROM sys.triggers
WHERE parent_id = OBJECT_ID('table_name');
删除触发器:
DROP TRIGGER trigger_name;
3. 查找特定表的存储过程
- 查询当前数据库中的所有存储过程:
SELECT name
FROM sys.procedures;
- 通过表名查询触发器:
使用sys.sql_modules视图和OBJECT_DEFINITION函数
SELECT OBJECT_NAME(object_id) AS ProcedureName
FROM sys.sql_modules
WHERE OBJECT_DEFINITION(object_id) LIKE '%YourTableName%';
多加一个字段属性,可以给出详细的存储过程的定义
SELECT
OBJECT_NAME(m.object_id) AS ProcedureName,
m.definition AS ProcedureDefinition
FROM
sys.sql_modules m
WHERE
OBJECT_DEFINITION(m.object_id) LIKE '%ags.GateReservationDetail%';
- 通过触发器名称查询:
如果有多个名称,都可在in后面进行添加补充
SELECT
OBJECT_NAME(m.object_id) AS ProcedureName,
m.definition AS ProcedureDefinition
FROM
sys.sql_modules m
WHERE
OBJECT_NAME(m.object_id) IN ('View_JobOwner');
标签:触发器,object,OBJECT,Server,sys,SQL,id,SELECT
From: https://blog.csdn.net/weixin_47872288/article/details/140033760