清除某个数据库的所有数据库连接的存储过程 [ZT]
在我们利用代码还原或者删除数据库的时候,经常碰到因为还存在数据库连接而拒绝操作的情况,我为此特意写了一个存储过程用来清除某个数据库的所有数据库链接。
代码如下:
代码如下:
CREATE PROC L_spClearDbConnections
@DbName VARCHAR(30)
AS
--清除某个数据库的所有数据库连接
--RickyLin 2007-11-1
DECLARE @SPID INT
DECLARE @SqlForClear NVARCHAR(100)
DECLARE curID CURSOR FORWARD_ONLY READ_ONLY FOR (
SELECT SPID
FROM Master.dbo.SysProcesses
WHERE DB_Name(DBID) = @DbName)
OPEN curID
FETCH NEXT FROM curID INTO @SPID
WHILE @@Fetch_Status = 0
BEGIN
SET @SqlForClear = N'KILL ' + Cast(@SPID AS NVARCHAR(10))
EXEC sp_ExecuteSql @SqlForClear
IF @@Error = 0
PRINT '已清除连接:' + Cast(@SPID AS VARCHAR(10))
FETCH NEXT FROM curID INTO @SPID
END
CLOSE curID
DEALLOCATE curID
PRINT '对数据库“' + @DbName + '”的连接清除操作完毕'
@DbName VARCHAR(30)
AS
--清除某个数据库的所有数据库连接
--RickyLin 2007-11-1
DECLARE @SPID INT
DECLARE @SqlForClear NVARCHAR(100)
DECLARE curID CURSOR FORWARD_ONLY READ_ONLY FOR (
SELECT SPID
FROM Master.dbo.SysProcesses
WHERE DB_Name(DBID) = @DbName)
OPEN curID
FETCH NEXT FROM curID INTO @SPID
WHILE @@Fetch_Status = 0
BEGIN
SET @SqlForClear = N'KILL ' + Cast(@SPID AS NVARCHAR(10))
EXEC sp_ExecuteSql @SqlForClear
IF @@Error = 0
PRINT '已清除连接:' + Cast(@SPID AS VARCHAR(10))
FETCH NEXT FROM curID INTO @SPID
END
CLOSE curID
DEALLOCATE curID
PRINT '对数据库“' + @DbName + '”的连接清除操作完毕'