Author Topic: Renaming a SQL Server Database  (Read 6598 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Renaming a SQL Server Database
« on: February 22, 2009, 08:58:25 AM »
In Microsoft® SQL Server™ 2000, you can change the name of a database to be changed. Before you rename a database, you should make sure that no one is using the database and that the database is set to single-user mode. The name of the database can include any characters as long as they follow the rules for identifiers.

Transact-SQL Reference (SQL Server 2000)
sp_renamedb
Changes the name of a database.

Syntax
sp_renamedb [ @dbname = ] 'old_name' ,
    [ @newname = ] 'new_name'

Arguments
[@dbname =] 'old_name'

Is the current name of the database. old_name is sysname, with no default.

[@newname =] 'new_name'

Is the new name of the database. new_name must follow the rules for identifiers. new_name is sysname, with no default.

Return Code Values
0 (success) or a nonzero number (failure)

Permissions
Only members of the sysadmin and dbcreator fixed server roles can execute sp_renamedb.

Examples
This example changes the name of the accounting database to financial.

Code: [Select]
EXEC sp_renamedb 'accounting', 'financial'

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Re: Renaming a SQL Server Database
« Reply #1 on: February 23, 2009, 11:35:22 AM »
If you face the following error:
"database could not be exclusively locked to perform the operation"
you can use:

ALTER DATABASE <DBNAME>  SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
SP_RENAMEDB <oldname>,<Newname>
Go
ALTER DATABASE <NEWDBNAME>  SET MULTI_USER -- set back to multi user
GO