Exclusive access for Database Restores on SQL Server 2005
How many times have you tried to run a database restore on SQL Server 2005 only for it to fail because you don’t have exclusive access to the database (for whatever reason from SSMS being open to anything else)? Happens to me quite frequently. Here’s a handy piece of code to help prevent that:
1 2 3 4 | ALTER DATABASE xxxxxxxxxx SET SINGLE_USER WITH ROLLBACK IMMEDIATE; -- Your restore script here. ALTER DATABASE xxxxxxxxxx SET MULTI_USER WITH ROLLBACK IMMEDIATE; GO |
What this does is sets the database into single-user mode (which effectively kills all other connections to it), restores the database, then when it’s done it sets it back to multi-user mode. I LOVE using this for restores that I seem to do over and over.