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

代码如下:

-- 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信息。

相关推荐