我想重命名一个数据库,但不断得到“无法获得数据库上的排他锁”的错误,这意味着仍有一些连接处于活动状态。

如何杀死数据库的所有连接以便重命名它?


当前回答

您可以使用SP_Who命令杀死所有使用您的数据库的进程,然后重命名您的数据库。

其他回答

下面是如何在MS SQL Server Management Studio 2008(可能也适用于其他版本)中可靠地执行这类事情:

In the Object Explorer Tree, right click the root database server (with the green arrow), then click activity monitor. Open the processes tab in the activity monitor, select the 'databases' drop down menu, and filter by the database you want. Right click the DB in Object Explorer and start a 'Tasks -> Take Offline' task. Leave this running in the background while you... Safely shut down whatever you can. Kill all remaining processes from the process tab. Bring the DB back online. Rename the DB. Bring your service back online and point it to the new DB.

在对象资源管理器上的MS SQL Server Management Studio中,右键单击数据库。在下面的上下文菜单中选择“任务->脱机”

Adam建议的方法不起作用的原因是,在循环活动连接的时间内,可以建立新的连接,而您将错过这些连接。你可以使用下面的方法,它没有这个缺点:

-- set your current connection to use master otherwise you might get an error

use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

--do you stuff here 

ALTER DATABASE YourDatabase SET MULTI_USER

试试这个:

ALTER DATABASE [DATABASE_NAME]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE

脚本来完成这个任务,用数据库替换'DB_NAME'来杀死所有连接到:

USE master
GO

SET NOCOUNT ON
DECLARE @DBName varchar(50)
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''

Set @DBName = 'DB_NAME'
IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)

IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
END