您的位置:首页 > 其它

kill all user in a database, very useful

2009-12-08 17:28 351 查看
It's very useful to tackle a locked database, when you decide to restore it.

Declare @tblConnectedUsers Table (
SPID int )

Declare @vcSQLText varchar(200),
@iSPID int

--Get the currently connected users
Insert into @tblConnectedUsers
Select p.spid
from master.dbo.sysprocesses p (nolock)
join master..sysdatabases d (nolock) on p.dbid = d.dbid
Where d.[name] = 'dbname' --> database name here

--Loop though the connected users and kill their connections
While 1 = 1
Begin

Select top 1 @iSPID = SPID
From @tblConnectedUsers
Where SPID > IsNull(@iSPID, 0)
order by SPID asc

-- break when there are no more SPIDs
If @@RowCount = 0
Break

--Build the SQL string
Set @vcSQLText = 'Kill ' + Convert(varchar(10), @iSPID)

Exec( @vcSQLText )

End
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐