我想关闭与MS SQL Server的现有连接,以便我可以以编程方式对该数据库进行恢复。
答案 0 :(得分:63)
这应该与其他人断开连接,并让您成为唯一的用户:
alter database YourDb set single_user with rollback immediate
注意:别忘了
alter database YourDb set MULTI_USER
完成后!
答案 1 :(得分:16)
单击“关闭与目标数据库的现有连接”
在分离数据库向导中单击“删除连接”项。答案 2 :(得分:4)
在这里找到它: http://awesomesql.wordpress.com/2010/02/08/script-to-drop-all-connections-to-a-database/
DECLARE @dbname NVARCHAR(128)
SET @dbname = 'DB name here'
-- db to drop connections
DECLARE @processid INT
SELECT @processid = MIN(spid)
FROM master.dbo.sysprocesses
WHERE dbid = DB_ID(@dbname)
WHILE @processid IS NOT NULL
BEGIN
EXEC ('KILL ' + @processid)
SELECT @processid = MIN(spid)
FROM master.dbo.sysprocesses
WHERE dbid = DB_ID(@dbname)
END
答案 3 :(得分:2)
Stev.org提供的完美解决方案: http://www.stev.org/post/2011/03/01/MS-SQL-Kill-connections-by-host.aspx
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KillConnectionsHost]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[KillConnectionsHost]
GO
/****** Object: StoredProcedure [dbo].[KillConnectionsHost] Script Date: 10/26/2012 13:59:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[KillConnectionsHost] @hostname varchar(MAX)
AS
DECLARE @spid int
DECLARE @sql varchar(MAX)
DECLARE cur CURSOR FOR
SELECT spid FROM sys.sysprocesses P
JOIN sys.sysdatabases D ON (D.dbid = P.dbid)
JOIN sys.sysusers U ON (P.uid = U.uid)
WHERE hostname = @hostname AND hostname != ''
AND P.spid != @@SPID
OPEN cur
FETCH NEXT FROM cur
INTO @spid
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CONVERT(varchar, @spid)
SET @sql = 'KILL ' + RTRIM(@spid)
PRINT @sql
EXEC(@sql)
FETCH NEXT FROM cur
INTO @spid
END
CLOSE cur
DEALLOCATE cur
GO
答案 4 :(得分:2)
您可以像这样使用Cursor:
USE master
GO
DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'
DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database
OPEN Murderer
FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
EXEC (@SQL)
PRINT ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
FETCH NEXT FROM Murderer INTO @SPID
END
CLOSE Murderer
DEALLOCATE Murderer
我在我的博客中写到:http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor
答案 5 :(得分:0)
仅在“ 数据库上下文 >> 还原向导”中获得“ 关闭与目标数据库的现有连接”选项,并且不任何特定数据库的ON上下文。
右键单击,如下所示:
,然后从中选择选项:“ 还原数据库... ”。
在“还原数据库”向导中,
在这里您可以找到以下复选框:“ 关闭与目标数据库的现有连接”
只需对其进行检查,即可继续进行还原操作。
还原完成后,它将自动恢复所有连接。
答案 6 :(得分:0)
在SQL Server Management Studio的最新版本中,您现在可以右键单击数据库,然后“使数据库脱机”。这使您可以选择删除所有到数据库的活动连接。