SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL Rename Database

Back to: SQL Server Tutorial

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)

  1. 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;
  2. 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 the ALTER DATABASE command.

  3. 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)

  1. Set the Database to Single-User Mode:

    ALTER DATABASE [OldDatabaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  2. Rename the Database:

    ALTER DATABASE [OldDatabaseName] MODIFY NAME = [NewDatabaseName];
  3. 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.

Scroll to Top