How to rename database without first stopping SQL instance to flush connections

Posted by John Galt on Server Fault See other posts from Server Fault or by John Galt
Published on 2010-06-12T18:11:22Z Indexed on 2010/06/12 18:23 UTC
Read the original article Hit count: 301

Is there a way to force a database into single user mode so a script can be run to rename databases? I find I have to Restart the instance of SQL (to force off any connections from a web app, etc.) and then I can run this script:

USE master
go
sp_dboption MDS, "single user", true
go
sp_dboption StagingMDS, "single user", true
go
sp_renamedb MDS, LastMonthMDS
go
sp_renamedb StagingMDS, MDS
go
sp_dboption LastMonthMDS, "single user", false
go
sp_dboption MDS, "single user", false
go

After this script runs, I can restart IIS for my web app and it can connect to the new production database.

All the above works well and we've been doing this for years but now we've upgraded to SQL 2008 and the SQL2008 instance also hosts other databases that support other web apps.

So, rather than using a Restart of the whole SQL instance to enable subsequent single-user mode on 2 databases, is there a less intrusive way of accomplishing this? Thanks.

© Server Fault or respective owner

Related posts about sql-server

Related posts about sql-server-2008