T-SQL 关闭数据库所有连接
原文引用自: http://www.cnblogs.com/kissazi2/p/3462202.html
下面给出一种删除数据库活动连接的方式。将下面代码段中的“--修改一下”处的数据库名修改成自己的数据库名。
USE master go IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[P_KillConnections]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) DROP PROCEDURE [dbo].[P_KillConnections] GO CREATE PROC P_KillConnections @dbname VARCHAR(200) AS DECLARE @sql NVARCHAR(500) DECLARE @spid NVARCHAR(20) DECLARE #tb CURSOR FOR SELECT spid=CAST(spid AS VARCHAR(20)) FROM master..sysprocesses WHERE dbid=DB_ID(@dbname) OPEN #tb FETCH NEXT FROM #tb INTO @spid WHILE @@fetch_status = 0 BEGIN EXEC('kill '+@spid) FETCH NEXT FROM #tb INTO @spid END CLOSE #tb DEALLOCATE #tb go --修改一下 EXEC P_KillConnections '修改成自己的数据库'