How to Kill All Processes That Have Open Connection in a SQL Server Database[关闭数据库链接 最佳方法] -摘自网络
SQL Server database administrators may frequently need in especially development and test environments instead of the production environments to kill all the open connections to a specific database in order to process SQL Server maintenance task over the SQL Server database.
In such situations when you need to kill or close all the active or open connections to the SQL Server database, you may manage this task by using the Microsoft SQL Server Management Studio or by running t-sql commands or codes. Actually, this task can be thought as a batch task to kill sql process running on a SQL Server.
If you open the SQL Server Management Studio and connect to a SQL Server instance you will see the Activity Monitor object in the Object Explorer screen of the related database instance. You can double click the Activity Monitor object or right click to view the context menu and then select a desired item to display the activities to be monitored on the Activity Monitor screen.
As seen on below you can monitor and view process id's and process details on the list of prcesses running on the database instance. If you want you can filter processes based on specific values like user, database or status.
Note that default view when displayed the screen is first opened is filtered only for non-system processes which means system processes which own the first 50 reserved processid's are not listed in the view by default. You can view system processes by removing the filter on "Show System Processes" criteria in the filter settings screen.
SQL Server 2005 SQL Server Management Studio Activity Monitor screen
You can kill a process by a right click on the process in the grid and selecting the Kill Process menu item. You will be asked for a confirmation to kill the related process and then will kill the open connection to the database over this process. This action is just like running to kill sql process t-sql command for a single process.
A second method which I do not recommend but can be used in some situations may be using the Detach Database screen to drop connections and detaching the database and then re-attaching the database. You can open the Detach Database screen from the context menu displayed by a right click on the related daabase for example for the below screen shot the name of the database is Works. On the menu, highlight menu item Tasks then select the Detach... menu item. This selection will open the detach database dialog screen. Note that if in the message column it is declared that active connections exists as for our case the number of active connections is 2, you will not be able to detach the database unless the Drop Connections checkbox is also selected.
The above configuration as the Drop Connections check box is cleared and active connections exist, the detach task will fail:
Detach database failed for Server '{DatabaseInstanceName}'. (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server& ProdVer=9.00.2047.00& EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates. FailedOperationExceptionText& EvtID=Detach+database+Server& LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
Cannot detach the database '{DatabaseName}' because it is currently in use. (Microsoft SQL Server, Error: 3703)
But if the Drop Connections is selected you can successfully detach the database. Then you will have to re-attach the database by selecting the Attach command from the context menu item displayed on the Databases node of the SQL Server instance.
For SQL Server 2000 the default behaviour was different than the SQL Server 2005. Because in SQL Server 2000, when you run the detach command from the menu item, you are prompted if you want to drop all active connections. Then you can confirm closing of all open connections, but the nice thing is that you can cancel detach process after the open connections are dropped or closed. But for SQL Server 2005, this behaviour is not valid.
How to Kill All Processes using T-SQL Code
By using t-sql commands or sql codes, similarly closing connections can be implemented by a few methods. One of the methods is using a cursor which loops for all the active connections of the related database and kill these processes. This method was also mention on SQL Server article named How to Alter a SQL Server Database as Single User Mode and as Multi User Mode
The below code block can be used to kill all processes which are connected to the sql database named @DatabaseName except the process that the code block is running in the scope of. You can also set the SQL Server database name by the DB_NAME() property.
The base of the below t-sql script is sql Kill SPId command. Within the sql cursor which loops through each process in sysProcesses view, each time a tsql Kill process command is called passing the SPId as an argument. And after Kill SPId sql statement is executed for each process, all database connections are dropped.
SQL Server database administrators can use below t-sql script in order to drop connections SQL Server 2008, or SQL Server 2005 and also drop connections to sql server 2000 database.
DECLARE @DatabaseName nvarchar(50) DECLARE @SPId int DECLARE @SQL nvarchar(100)
--SET @DatabaseName = N'AdventureWorks2008' SET @DatabaseName = DB_NAME() DECLARE my_cursor CURSOR FAST_FORWARD FOR SELECT SPId FROM MASTER..SysProcesses WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @SPId
WHILE @@FETCH_STATUS = 0 BEGIN SET @SQL = 'KILL ' + CAST(@SPId as nvarchar(10)) print @SQL EXEC sp_executeSQL @SQL --KILL @SPId -- Causing Incorrect syntax near '@spid'.
FETCH NEXT FROM my_cursor INTO @SPId END
CLOSE my_cursor DEALLOCATE my_cursor
UPDATE : Please note that I altered above t-sql script and removed KILL @SPId sql statement. It was causing the below error. Msg 102, Level 15, State 1, Line 19 Incorrect syntax near '@SPId'. This is because the sql processid can not be used using a variable with sql KILL command. The solution is using dynamic t-sql statement as shown in the above sql cursor code.
A second way to drop all active connections of a database can be implemented by generating dynamic sql commands that runs a list of "Kill @spId" commands.
DECLARE @DatabaseName nvarchar(50) SET @DatabaseName = N'Works' --SET @DatabaseName = DB_NAME()
DECLARE @SQL varchar(max) SET @SQL = ''
SELECT @SQL = @SQL + 'Kill ' + Convert(varchar, SPId) + ';' FROM MASTER..SysProcesses WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
-- SELECT @SQL EXEC(@SQL)
A very similar to the sql code above, an other code block can be used by using the COALESCE as shown below
DECLARE @DatabaseName nvarchar(50) SET @DatabaseName = N'Works'
DECLARE @SQL varchar(max)
SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';' FROM MASTER..SysProcesses WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
--SELECT @SQL EXEC(@SQL)
The above sql queries can be modified further for specific needs. For example you may create a sql stored procedure that drops all existing active connections. You may pass SQL database name or database id as parameter or use the current database information to kill processes except its own process, etc.
How to Kill All Processes That Have Open Connection in a SQL Server Database[关闭数据库链接 最佳方法] -摘自网络的更多相关文章
- (转)How To Kill runaway processes After Terminating Concurrent Request
终止EBS并发请求后,解锁相关的进程. 还有种方法可以在PLSQL->tools->session 中找到并且kill Every concurrent Request uses some ...
- SQL Server会话KILL不掉,一直处于KILLED /ROLLBACK状态情形浅析
今天遇到一个很奇怪的情况,发现一个会话异常,这个会话只是在执行一个简单的存储过程,里面使用了链接服务器(Linked Server)查询另外一台服务器数据(存储过程里面没有任何显性事务.UPDATE. ...
- sql server block如何查询并kill
本帖提供两种做法,可避免在 SQL Server 事务锁定时产生的不正常或长时间阻塞,让用户和程序也无限期等待,甚至引起 connection pooling 连接数超过容量. 所谓的「阻塞」,是指当 ...
- SQL Server会话KILL不掉,一直处于KILLED /ROLLBACK状态情形浅析[转]
本文将为您描述SQL Server会话KILL不掉,一直处于KILLED /ROLLBACK状态情形浅析,教程操作方法: 今天遇到一个很奇怪的情况,发现一个会话异常,这个会话只是在执行一个简单的存储过 ...
- sql server 查看表的死锁和Kill 死锁进程
查询出来 select request_session_id spid, OBJECT_NAME(resource_associated_entity_id) tableNa ...
- sql server 查询和Kill死锁进程
查询死锁进程语句 select request_session_id spid, OBJECT_NAME(resource_associated_entity_id) tab ...
- SQL Server查询死锁并KILL
杀掉死锁的sqlserver进程 SELECT request_session_id spid,OBJECT_NAME (resource_associated_entity_id)tableNa ...
- Sql server 查看锁和Kill 死锁进程
死锁的概念 死锁就是两个或多个会话(SPID)相互请求对方持有的锁资源,导致循环等待的情况.下面两种方法都是用来粗暴的解决死锁的. # 已知阻塞进程ID KILL ID SELECT blocking ...
- SHUTDOWN: Active processes prevent shutdown operation
在使用shutdown immediate关闭数据库时hang住,查看alert 日志,遭遇了SHUTDOWN: Active processes prevent shutdown operation ...
随机推荐
- poj 2778 DNA Sequence ac自动机+矩阵快速幂
链接:http://poj.org/problem?id=2778 题意:给定不超过10串,每串长度不超过10的灾难基因:问在之后给定的长度不超过2e9的基因长度中不包含灾难基因的基因有多少中? DN ...
- 3.bit-map
适用范围:可进行数据的快速查找,判重,删除,一般来说数据范围是int的10倍以下 基本原理及要点:使用bit数组来表示某些元素是否存在,比如8位电话号码 扩展:bloom filter可以看做是对bi ...
- 素数筛&&欧拉筛
折腾了一晚上很水的数论,整个人都萌萌哒 主要看了欧拉筛和素数筛的O(n)的算法 这个比那个一长串英文名的算法的优势在于没有多次计算一个数,也就是说一个数只筛了一次,主要是在%==0之后跳出实现的,具体 ...
- JDBC和DBUtils区别(查询时jdbc只能返回ResultSet需要po转vo,dbutils返回的BeanListHandler与BeanHandler对应集合与对象)
17:34 2013/6/7 JDBC //添加客户 public void addNewCustomer(Customer c) throws DAOException { Connection c ...
- Objective-c开发中混合使用ARC
首选“Compile Sources”的位置: 选中工程->TARGETS->相应的target然后选中右侧的“Build Phases”,向下就找到“Compile Sources”了. ...
- Grails默认首页的修改
有些人使用IDEA开发Grails,开发阶段使用Grails自带的默认首页可以方便我们开发,但是开发结束后想要修改默认的首页,如何修改呢? 1.打开grails-app 文件下conf下的UrlMap ...
- SGU481 Hero of Our Time
Description Saratov ACM ICPC teams have a tradition to come together on Halloween and recollect terr ...
- 对话 Jessica Hamrick:和 Django 的情缘是我前行的动力
本文出自 Your Django Story 系列,该系列主要突出那些贡献 Django 的女性.点击查看更多,本文系 OneAPM 工程师编译整理. Jess Hamrick 是加州大学伯克利分校心 ...
- ***PHP请求服务curl以及json的解析
对于thinkphp框架,相信每一个php开发者都会有了解或者熟悉吧!前端很多都用的ajax的结合,前几天遇到了一个问题,就是请求另一个服务,也就是请求一个接口,然后对方返回一个json串,一开始对c ...
- 酷盘kanbox获得B轮2000万美元融资
和阿里近期收购以穷游.虾米为代表的一批小网站相似,酷盘也属于个人用户数量级别庞大,但商业模式并不明晰的企业.目前阿里巴巴集团旗下的阿里云公司拥有自己的云存储业务,其本身既有面向个人用户的产品,也有面向 ...