站长资源数据库

SQLServer EVENTDATA()函数来获取DDL 触发器信息

整理:jimmy2024/12/25浏览2
简介复制代码 代码如下:-- Create a log table CREATE TABLE TriggerLog (LogInfo xml) -- Create a dummy table to delete later on CREATE TABLE TableToDelete (Id int PR
复制代码 代码如下:
-- Create a log table
CREATE TABLE TriggerLog (LogInfo xml)

-- Create a dummy table to delete later on
CREATE TABLE TableToDelete (Id int PRIMARY KEY)

-- 新建一个新表,作为删除实验表
INSERT INTO TableToDelete VALUES(1)
GO

-- 创建一个Drop Table 的 DDL
CREATE TRIGGER StopTableDrop ON DATABASE AFTER DROP_TABLE
AS
DECLARE @EventData AS xml
SET @EventData = EVENTDATA() -- 必须要在rollback之前截获DDL信息
ROLLBACK
PRINT 'DROP TABLE attempt in database ' + DB_NAME() + '.'
INSERT INTO TriggerLog VALUES(@EventData)

执行如下删除操作:
DROP TABLE TableToDelete
会触发上面的DDL,从而回滚操作。
执行下面的Sql:
SELECT * FROM TriggerLog
查看刚才截获的DDL信息。