SQL Server 2005中,新增加了許多新的特性,其中的DDL觸發器是個不錯的選擇,根據資料初步學習如下,現整理之。
在sql server 2000中,只能為針對表發出的 DML 語句(INSERT、UPDATE 和 DELETE)定義 AFTER 觸發器。SQL Server 2005 可以就整個服務器或數據庫的某個范圍為 DDL 事件定義觸發器。
可以為單個 DDL 語句(例如,CREATE_TABLE)或者為一組語句(例如,DDL_DATABASE_LEVEL_EVENTS)定義 DDL 觸發器。在該觸發器內部,您可以通過訪問 eventdata() 函數獲得與激發該觸發器的事件有關的數據。該函數返回有關事件的 XML 數據。每個事件的架構都繼承了 Server Events 基礎架構。
比如,在SQL Server 2005中,建立一個叫DDLTrTest 的數據庫,並且建立一個叫mytable的表和Usp_Querymytable 的存儲過程,如下所示。
DROP DATABASE [DDLTRTEST]
GO
CREATE DATABASE DDLTRTEST
GO
USE [DDLTRTEST]
GO
IF EXISTS (SELECT * FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[MYTABLE]')
AND TYPE IN (N'U'))
DROP TABLE [DBO].[MYTABLE]
GO
CREATE TABLE MYTABLE(ID INT, NAME VARCHAR(100))
GO
INSERT INTO MYTABLE SELECT 1,'A'
INSERT INTO MYTABLE SELECT 2,'B'
INSERT INTO MYTABLE SELECT 3,'C'
INSERT INTO MYTABLE SELECT 4,'D'
INSERT INTO MYTABLE SELECT 5,'E'
INSERT INTO MYTABLE SELECT 6,'F'
GO
USE [DDLTrTest]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'[dbo].[usp_querymytable]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[usp_querymytable]
GO
CREATE PROC USP_QUERYMYTABLE
AS
SELECT * FROM MYTABLE
GO
接下來定義一個DDL觸發器如下
CREATE TRIGGER STOP_DDL_on_Table_and_PROC
ON DATABASE
FOR CREATE_TABLE,DROP_TABLE,
ALTER_TABLE,CREATE_PROCEDURE,
ALTER_PROCEDURE,DROP_PROCEDURE
AS
SELECT EVENTDATA().value
('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]',
'nvarchar(max)')
PRINT 'You are not allowed to CREATE,ALTER and DROP
any Tables and Procedures'
ROLLBACK;
接下來,我們嘗試如下的操作:
ALTER TABLE MYTABLE ADD X INT
結果如下,出現錯誤提示
ALTER TABLE MYTABLE ADD X INT
(1 row(s) affected)
You are not allowed to CREATE,ALTER and DROP any Tables and Procedures
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
再執行DROP的操作,同樣觸發警告
DROP TABLE MYTABLE
(1 row(s) affected)
You are not allowed to CREATE,ALTER and DROP any Tables and Procedures
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
因為我們的觸發器規定了不能使用CREATE_TABLE、DROP_TABLE、ALTER_TABLE、CREATE_PROCEDURE、ALTER_PROCEDURE、DROP_PROCEDURE等操作。 如果我們要關掉這個觸發器,可以這樣做:
DISABLE TRIGGER STOP_DDL_ON_TABLE_AND_PROC ON DATABASE
當然,我們要對整個服務器采取策略的話,也是很簡單的,和上面的方法大致相同只不過將on database的參數改為on server,比如
CREATE TRIGGER STOP_DDL_on_Table_and_PROC
ON ALL SERVER
FOR CREATE_DATABASE,ALTER_DATABASE,DROP_DATABASE
AS
PRINT 'You are not allowed to CREATE,ALTER and DROP any Databases'
ROLLBACK;