How do you kill all current connections to a SQL S

2019-01-04 15:17发布

I want to rename a database, but keep getting the error that 'couldn't get exclusive lock' on the database, which implies there is some connection(s) still active.

How can I kill all the connections to the database so that I can rename it?

19条回答
Bombasti
2楼-- · 2019-01-04 16:06

Right click on the database name, click on Property to get property window, Open the Options tab and change the "Restrict Access" property from Multi User to Single User. When you hit on OK button, it will prompt you to closes all open connection, select "Yes" and you are set to rename the database....

查看更多
We Are One
3楼-- · 2019-01-04 16:06

I've always used:


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 
查看更多
放荡不羁爱自由
4楼-- · 2019-01-04 16:07

I use sp_who to get list of all process in database. This is better because you may want to review which process to kill.

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

Result
You can use command in KillCommand column to kill the process you want to.

SPID    KillCommand
26      kill 26;
27      kill 27;
28      kill 28;
查看更多
Luminary・发光体
5楼-- · 2019-01-04 16:07
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

use the 'master' database and run this query, it will kill all the active connections from your database.

查看更多
叼着烟拽天下
6楼-- · 2019-01-04 16:09
ALTER DATABASE [Test]
SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER DATABASE [Test]
SET ONLINE
查看更多
Luminary・发光体
7楼-- · 2019-01-04 16:10

You can Use SP_Who command and kill all process that use your database and then rename your database.

查看更多
登录 后发表回答