DROP DATABASE的SQL Server警告

时间:2015-11-10 21:34:16

标签: sql-server tsql

如果在错误的SQL Server会话窗口中执行或使用错误的数据库名称,T-SQL中的DROP DATABASE <*dbname*>命令可能会造成伤害。

对于相当于旧DOS的情况来说似乎是一个很好的情况“你确定吗?”警告。

SQL Server中是否有任何可以为给定数据库设置此类内容的设置?

1 个答案:

答案 0 :(得分:3)

可能是DDL触发器,类似......

ALTER TRIGGER DB_Drop_Warnning 
ON ALL SERVER 
FOR DROP_DATABASE
AS 
DECLARE @DatabaseName NVARCHAR(100),
        @eventData XML

SET @eventData = EVENTDATA()            
SELECT @DatabaseName = @eventData.value('(/EVENT_INSTANCE/DatabaseName)[1]','varchar(128)')

IF @DatabaseName IN ('TEST_DB1','TEST_DB2','TEST_DB3')  --<-- your database name(s) here 
  BEGIN
    PRINT 'Disable the trigger before you can drop the database.' 
    ROLLBACK;
  END
GO

启用触发器:

 ENABLE TRIGGER [DB_Drop_Warnning] ON ALL SERVER 
 GO

现在,如果您尝试删除该数据库,则会抛出以下错误:

Disable the trigger before you can drop the database. 
Msg 3609, Level 16, State 2, Line 1 
The transaction ended in the trigger. The batch has been aborted.

如果要删除数据库,只需禁用触发器:

 DISABLE TRIGGER [DB_Drop_Warnning] ON ALL SERVER 
 GO