Renaming a database in Microsoft SQL Server is a straightforward process, but it does involve a few steps. Here's how you can do it:
Using SQL Server Management Studio (SSMS)
-
Ensure No Active Connections: Before renaming a database, make sure there are no active connections to it. You might need to set the database to single-user mode.
ALTER DATABASE [OldDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; -
Rename the Database: You can rename the database using the following command:
EXEC sp_renamedb 'OldDatabaseName', 'NewDatabaseName';Note:
sp_renamedb
is deprecated in newer versions of SQL Server. It's better to use theALTER DATABASE
command. -
Switch Back to Multi-User Mode: After renaming the database, you may want to set it back to multi-user mode:
ALTER DATABASE [NewDatabaseName] SET MULTI_USER;
Using Transact-SQL (T-SQL)
-
Set the Database to Single-User Mode:
ALTER DATABASE [OldDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; -
Rename the Database:
ALTER DATABASE [OldDatabaseName] MODIFY NAME = [NewDatabaseName]; -
Set the Database Back to Multi-User Mode:
ALTER DATABASE [NewDatabaseName] SET MULTI_USER;
Important Notes
- Backup: Always ensure you have a recent backup of your database before performing operations like renaming.
- Dependencies: Check for dependencies like linked servers, connection strings in your applications, or any scripts that reference the old database name.
- Permissions: Ensure you have sufficient permissions to perform these operations, typically requiring the
ALTER ANY DATABASE
permission.
By following these steps, you should be able to successfully rename your SQL Server database.