Answers:
有两种方法:
在对象资源管理器中右键单击数据库,转到“任务”>“分离”。选择断开连接复选框。
将数据库设置为单用户模式,如下所示:
-- hit Ctrl+Shift+M in SSMS to fill in the template parameter
USE master;
GO
ALTER DATABASE N'<Database Name, sysname,>'
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE N'<Database Name, sysname,>'
SET READ_ONLY;
GO
ALTER DATABASE N'<Database Name, sysname,>'
SET MULTI_USER;
GO
我总是使用以下内容:
USE master; -- get out of dbname myself
GO
-- kick all other users out:
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- prevent sessions from re-establishing connection:
ALTER DATABASE [dbname] SET OFFLINE;
有时这可能需要一段时间,有时会因为您正在运行而被阻止,并且您与数据库的连接处于活动状态。检查其他可能具有相同数据库上下文的查询窗口-其中可能包括打开的对话框,对象资源管理器,IntelliSense,长时间运行的作业等。
完成对数据库配置的更改后,我只需:
ALTER DATABASE [dbname] SET ONLINE;
ALTER DATABASE [dbname] SET MULTI_USER;
虽然有时我需要对该数据库执行的操作要求该数据库处于联机状态,所以有时我必须将其保留在单用户模式下并执行以下操作:
ALTER DATABASE [dbname] SET ONLINE;
GO
USE [dbname];
现在,我可以进行更改,然后在准备好其他用户连接时,只需:
ALTER DATABASE [dbname] SET MULTI_USER;
我通常在single_user中设置数据库,然后等待延迟,然后在多用户中设置数据库,如下所示:
-- to kill all connections for particular db ... otherwise the restore will fail as exclusive lock cannot be obtained for the db being restored.
alter database db_name
set single_user with rollback immediate
waitfor delay '00:00:05' -- wait for 5 secs
alter database db_name
set multi_user
restore database db_name from disk = 'D:\restore\db_name.bak'
with replace, stats = 10, recovery -- if you want to recover your database online
-- optional if you dont have the same directory/file structure
move 'datafile logical name' to 'E:\data\physical_name.mdf',
move 'logfile logical name' to 'F:\log\physical_name_log.ldf'
以下内容实际上会杀死所有连接。在设置单用户模式失败的情况下非常有用
declare @execSql varchar(1000), @databaseName varchar(100)
-- Set the database name for which to kill the connections
set @databaseName = 'databasename'
set @execSql = ''
select @execSql = @execSql + 'kill ' + convert(char(10), spid) + ' '
from master.dbo.sysprocesses
where db_name(dbid) = @databaseName
and
DBID <> 0
and
spid <> @@spid
exec(@execSql)
sysprocesses
它并不总是解决所有可能在该数据库中持有锁的会话(想想在数据库A的上下文中运行查询但将A中的表和B中的表连接起来的简单方案) 。
您可以使用以下脚本来核对所有人,或针对特定的数据库进行修改。
可以杀死的任何东西都将成为!但是,SQL服务SPID不会受到影响。
Drop table #who
go
Create table #who( [spid] int,
[ECID] int,
[Status] varchar(100),
[Loginname] varchar(200),
[Hostname] varchar(200),
[blk] bit,
dbname varchar(200),
cmd varchar(1000),
requestID int
)
go
Insert into #who (Spid, ECID, Status, Loginname, hostname,blk, dbname, cmd, requestid)
exec sp_who
Declare cursKillUsers Cursor for Select 'Kill ' + cast(spid as varchar(100)) + ';' [SQL] from #who where dbname like '%'
Declare @sql varchar(200)
Open cursKillUsers
Fetch next from cursKillUsers into @sql
While @@fetch_status = 0
begin
print @sql
Exec (@sql)
Fetch next from cursKillUsers into @sql
end
close cursKillUsers
deallocate cursKillUsers