Renaming your SQL Server Database

SQL Server - SeniorDBA

Renaming a SQL Server database is more difficult than you might be thinking. Sure, it is easy to change the name of the database in SSMS, or even by executing a script:

USE master
GO
ALTER DATABASE YOURDATABASENAME 
SET SINGLE_USER 
WITH ROLLBACK IMMEDIATE
GO
EXEC master..sp_renamedb 'YOURDATABASENAME','YOUR_NEW_DATABASE_NAME'
GO
ALTER DATABASE YOUR_NEW_DATABASE_NAME 
SET MULTI_USER 
GO

The difficulty comes from changing every place that old database name exists, which includes the database file name, the log file name, etc.

This article by Hannes du Preez provides the scripts for changing the file names.

ALTER DATABASE YOURDATABASENAME SET SINGLE_USER WITH ROLLBACK IMMEDIATE
-- Change Logical File Name 
ALTER DATABASE [YOURDATABASENAME] MODIFY FILE (NAME=N'YOURDATABASENAME', NEWNAME=N'YOUR_NEW_DATABASE_NAME')
GO
ALTER DATABASE [YOURDATABASENAME] MODIFY FILE (NAME=N'YOURDATABASENAME_log', NEWNAME=N'YOUR_NEW_DATABASE_NAME_log')
GO

--Detach
GO
EXEC master.dbo.sp_detach_db @dbname = N'YOURDATABASENAME'
GO

--Rename
EXEC xp_cmdshell 'RENAME "C:\Program Files\Microsoft SQL ServerMSSQL10.SQL2008\
MSSQL\DATA\YOURDATABASENAME.mdf", "YOUR_NEW_DATABASE_NAME.mdf"'
GO
EXEC xp_cmdshell 'RENAME "C:\Program Files\Microsoft SQL ServerMSSQL10.SQL2008\
MSSQL\DATA\YOURDATABASENAME_log.ldf", "YOUR_NEW_DATABASE_NAME_log.ldf"'
GO

--Attach
CREATE DATABASE YOUR_NEW_DATABASE_NAME ON 
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\YOUR_NEW_DATABASE_NAME.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\YOUR_NEW_DATABASE_NAME_log.ldf' )
FOR ATTACH
GO
ALTER DATABASE YOUR_NEW_DATABASE_NAME SET MULTI_USER 
GO
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s