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

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


当前回答

在这种情况下,适合我的选项如下:

在相关数据库上启动“Detach”操作。这将打开一个窗口(在SQL 2005中),显示阻止对DB执行操作的活动连接。 终止活动连接,取消分离操作。 现在应该可以恢复数据库了。

其他回答

这些对我不起作用(SQL2008 Enterprise),我也看不到任何正在运行的进程或连接到DB的用户。重新启动服务器(右键单击Management Studio中的Sql server并选择重新启动)允许我恢复DB。

我总是用:


ALTER DATABASE DB_NAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO 
SP_RENAMEDB 'DB_NAME','DB_NAME_NEW'
Go 
ALTER DATABASE DB_NAME_NEW  SET MULTI_USER -- set back to multi user 
GO 

下面是如何在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.

右键单击数据库名称,单击属性进入属性窗口,打开选项选项卡,将“限制访问”属性从多用户更改为单用户。当你点击OK按钮时,它会提示你关闭所有打开的连接,选择“是”,你就可以将数据库重命名为....

试试这个:

ALTER DATABASE [DATABASE_NAME]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE