The Microsoft SQL Server provides you multiple ways to rename a database. You can either use SQL Server management studio or run SQL query to rename a database. Before renaming a database, remember it can break the connections for services configured with the current database name or existing stored procedures.
How to Rename a SQL Server Database
In this guide, we will discuss three ways to rename a database in the SQL server. The first option will use SQL query to rename a database, the second will use a stored procedure and the third option will use SQL Server Management Studio (SSMS) to rename a database.
Use one of the below options’s to rename a SQL server database:
1. Rename SQL Database with Query
Use ALTER DATABASE query to rename a database in SQL Server. The renaming process will fail, in case there are any active connections established by applications or other databases.
Use the below queries to rename the database with SQL query. The first query will change the database to single-user mode to prevent any external connection. After that rename, the database and again set the database to multi-user mode.
ALTER DATABASE Test_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO ALTER DATABASE [Test_db] MODIFY NAME = [Test_db2] GO ALTER DATABASE Test_db_new SET MULTI_USER; GO
That’s it. You will see that database is renamed.
2. Rename SQL Database with Stored Procedure
The SQL server will also provide a stored procedure to rename a database. You can follow the same way as above to switch the database to single-user mode and rename the database.
The database rename queries will be like:
ALTER DATABASE Test_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO EXEC sp_renamedb 'Test_db', 'Test_db2' GO ALTER DATABASE Test_db_new SET MULTI_USER; GO
3. Rename SQL Database with Management Studio
You can also rename the SQL server database similar to renaming a folder in Windows. Open SQL Server Management Studio (SSMS) and connect to the database server. Follow the below steps to change SQL server to single user mode and rename a database.
First, we will set the database connection to single-user mode to close all active connections to the database before renaming. So follow the below steps to rename the SQL database with SSMS.
The steps are:
- Open Object Explorer in SSMS.
- Right Click on the database and click on properties.
- In the Properties, select the Options page
- From the Restrict Access option, select Single.
- Again, right-click the Database and click on Rename.
- Enter a new name for database and hit enter.
- Again, open Options page in properties and change Restrict Access to MULTI_USER
Here is the screenshots for the above steps:
Open the SQL Server database properties:
Restrict database access to SINGLE_USER in SQL Server.
Select rename option in SQL server database properties.
Finally, rename the SQL Server database.
This tutorial helped you with 3 methods to rename a database in the SQL Server on the Windows system.