Sql-server – How to rename database without first stopping SQL instance to flush connections

database-administrationrenamesql serversql-server-2008

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.

Best Answer

This should kill any open connections to the database:

alter database mds set single_user with rollback immediate