SQL Server中使用SQL语句关闭数据库连接和删除数据库文件

时间:2024-03-07 19:27:00

有时候我们想用DROP DATABASE语句删除数据库和数据库文件,会删不掉,因为有其他人正在使用要删除的数据库,这里有一个方法可以强制断开其它数据库连接,再删除数据库。

假如我们要删除的数据库是[TestDB],我们可以用下面的语句:

USE [master]--注意不能够USE [TestDB],因为[TestDB]即将被删除,所以不能够将当前连接设置为连接到[TestDB],否则下面的DROP DATABASE语句会报错

ALTER DATABASE [TestDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;--首先将数据库改为单用户模式,WITH ROLLBACK IMMEDIATE提示切断所有其它连接到[TestDB]的数据库连接
DROP DATABASE [TestDB];--删除[TestDB]及其数据库文件

所以这个方法的核心就是先更改数据库模式为单用户模式"SINGLE_USER",那么什么是数据库的单用户模式呢?我这里贴出一个从网上找到的解释:

So in single_user mode - you would be quite unlikely to have locking problems in that database. It is what it sounds like - single user - and it doesn\'t mean Single Username - it means one user. So it\'s used when you as a DBA want to do something that can\'t be done with others users in. Maybe you are trying to do a repair option of a checkdb. Maybe you are trying to change some object metadata and don\'t have a better way to kick other users out. Etc.

上面的解释来自:What happens when SQL Server is in Single User Mode?

所以数据库单用户模式"SINGLE_USER",是指只能有一个用户连接能够连接到数据库,这样我们就可以在没有其它数据库连接的情况下,执行DROP DATABASE语句来删除数据库和其数据库文件了。