Wednesday, October 08, 2008

Gaining Exclusive Access to database in SQL Server 2005 via T-SQL

Usually, whenever I restore a backup of my database in SQL Server I am presented with the following error:

Msg 3101, Level 16, State 1, Line 1
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.

Usually, to get around this I just restart the server. This was fine when we were developing on our local server instance on our development machines. But we have a few programmers that need to make changes to the database and the logistics of having everyone script their changes and drop them into Subversion was becoming a nightmare. Regardless our simple solution was to put it on a shared server in the office and backup the server occasionally, in case someone screwed up the data.

Well I screwed up some data and needed to restore. Unfortunately, I have another co-worker in the office who is working on another project and is using the same database server (different database) for development. To be nice I'd want to restore without restarting the SQL Server and possibly disrupting his work.

What I need to do is find all the connection processes to the database and kill them:

Use Master
Go

Declare @dbname sysname

Set @dbname = 'databaseName'

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

Now I can immediately restore:

USE Master
GO
RESTORE DATABASE [databaseName]
FROM  DISK = N'physical disk path to the backup file.bak' --example path: c:\program files\microsoft sql server\mssql\backup\databaseName.bak
WITH  FILE = 1,  NOUNLOADREPLACESTATS = 10
GO

This method works best in a development environment with minimum developer connections. In production/staging environments refer to your database administrator for best practices.


Related Links

How to Gain Exclusive Access to SQL Server 2005 DB to restore?

Tuesday, November 11, 2008 3:33:05 AM (Eastern Standard Time, UTC-05:00)
works for me, thanks
EV
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):

Blog Posts by:

Currently Viewable:

My Twitter Updates

View Twitter Page