MSSQL: What if your DB is locked?

This topic is based on http://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database

1. This receipt usually works for me:

ALTER DATABASE [YourDB]
SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER DATABASE [YourDB]
SET ONLINE

2. This method is claimed to work as well (haven't checked):

use master
ALTER DATABASE YourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

--do you stuff here

ALTER DATABASE YourDB SET MULTI_USER

3. With kill syntax (haven't checked):

USE master
go

DECLARE @dbname sysname
SET @dbname =  'YourDB '

DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END

Comments

Popular Posts