I had to rename a database recently and googled the result. There are many usual resources and with ready-to-use examples. I will record them here for my own references and at mean time, I will add more details on what the commands do.
With renaming database, we need to set the database to single user mode first. Once the name is changed, we will set the multi-user mode back to the database.
This script does just that for SQL Server 2000:
ALTER DATABASE orig_db_name SET SINGLE_USER WITH ROLLBACK IMMEDIATE
EXEC sp_renamedb 'orig_db_name', 'new_db_name'
ALTER DATABASE new_db_name SET MULTI_USER
SQL Server 2005+ should use this slightly different version:
ALTER DATABASE orig_db_name SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE orig_db_name MODIFY NAME = new_db_name
ALTER DATABASE new_db_name SET MULTI_USER
First of all, I would like talk about the single user mode. If this mode is on, this means only one user can connect to the SQL server at one time. It will enable the user to change any server configuration or recover a damaged master database or other system database. Single user mode can also be set via the main plan configured on the SQL instance with Check Database Integrity task in the plan along with the “attempt to repair minor problems” option enabled. This will put the database in single user mode before executing CHECKDB.
However, sometimes, it is also can be a pain as if the connection is overtaken by another user, the actual user will not be able to logon and we need to seek other solution to break in e.g., kill the other process first, etc.
Meanwhile, the single user mode can also be stuck and you may not able to set the multi-user mode back on. See this post for a good example http://blogs.msdn.com/b/dfurman/archive/2012/01/20/getting-out-of-single-user-mode.aspx.
The next is the WITH ROLLBACK IMMEDIATE clause. It is a clause that we do not use usually but it is quite helpful. This simply means that if you would like to roll back immediately or not. There are another two options here.
Option 1: WITH ROLLBACK AFTER integer [SECONDS] – this means the transaction will still roll back if it encounters problem but within the seconds specified.
Option 2: WITH NO_WAIT – it simply means the transaction will not wait and if it encounters problem it will fail immediate without wait for roll back or commit.