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

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


当前回答

我使用sp_who来获取数据库中所有进程的列表。这样更好,因为您可能需要检查要终止哪个进程。

declare @proc table(
    SPID bigint,
    Status nvarchar(255),
    Login nvarchar(255),
    HostName nvarchar(255),
    BlkBy nvarchar(255),
    DBName nvarchar(255),
    Command nvarchar(MAX),
    CPUTime bigint,
    DiskIO bigint,
    LastBatch nvarchar(255),
    ProgramName nvarchar(255),
    SPID2 bigint,
    REQUESTID bigint
)

insert into @proc
exec sp_who2

select  *, KillCommand = concat('kill ', SPID, ';')
from    @proc

结果 您可以使用KillCommand列中的命令来终止您想要的进程。

SPID    KillCommand
26      kill 26;
27      kill 27;
28      kill 28;

其他回答

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

Select 'Kill '+ CAST(p.spid AS VARCHAR)KillCommand into #temp
from master.dbo.sysprocesses p (nolock)
join master..sysdatabases d (nolock) on p.dbid = d.dbid
Where d.[name] = 'your db name'

Declare @query nvarchar(max)
--Select * from #temp
Select @query =STUFF((                              
            select '  ' + KillCommand from #temp
            FOR XML PATH('')),1,1,'') 
Execute sp_executesql @query 
Drop table #temp

使用'master'数据库并运行此查询,它将杀死数据库中的所有活动连接。

下线需要一段时间,有时我会遇到一些问题。

在我看来最可靠的方法是:

分离 右键单击DB -> Tasks -> Detach… 检查“删除连接” 好吧

重新接上 右键单击数据库->附加.. 添加……->选择您的数据库,并将Attach As列更改为所需的数据库名称。 好吧

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

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