Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename database in multi-user mode

I am working on SQL SERVER 2008 & 2008 R2. How can I rename a database in multi-user mode? I am using sp_rename but it returns this error:

Msg 15225, Level 11, State 1, Procedure sp_rename, Line 338

like image 275
Vikrant More Avatar asked Jun 13 '12 11:06

Vikrant More


People also ask

How do I change a SQL database from one user to another?

Use SQL Server Management StudioRight-click the database to change, and then select Properties. In the Database Properties dialog box, select the Options page. From the Restrict Access option, select Single. If other users are connected to the database, an Open Connections message will appear.

Can I rename a SQL Server database?

If you are using SQL Server Management Studio, right click on the database and select the Rename option and then rename the database.


1 Answers

You can't rename a database while it is in use. Either wait for a maintenance window, or force the database to single user mode (which will kick everyone out):

USE [master];
GO
ALTER DATABASE foo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
--EXEC sys.sp_renamedb @dbname = N'foo', @newname = N'bar';
ALTER DATABASE foo MODIFY NAME = bar; -- preferred way
GO
ALTER DATABASE bar SET MULTI_USER;
like image 171
Aaron Bertrand Avatar answered Oct 06 '22 16:10

Aaron Bertrand