USE [master]
GO
/* Important to get logical and physical file names */
SELECT name AS [Logical Name]
,physical_name AS [DB File Path]
,type_desc AS [File Type]
,state_desc AS [State]
FROM sys.master_files
WHERE database_id = DB_ID(N'VladTesting')
GO
Logical Name | DB File Path | File Type | State |
---|---|---|---|
VladTesting | C:\SQL Server Data Files\MSSQL11\Data\VladTesting.mdf | ROWS | ONLINE |
VladTesting_log | C:\SQL Server Data Files\MSSQL11\Log\VladTesting_log.ldf | LOG | ONLINE |
ALTER DATABASE VladTesting
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE [VladTesting] MODIFY FILE
(NAME=N'VladTesting', NEWNAME=N'VladsAwesomeDB')
GO
ALTER DATABASE [VladTesting] MODIFY FILE
(NAME=N'VladTesting_log', NEWNAME=N'VladsAwesomeDB')
GO
Another option is to take DB Offline and rename files and later rename DB.
EXEC master.dbo.sp_detach_db @dbname = N'VladTesting'
GO
Most of the time XP_CMDSHELL is not enable as it is considered dangerous, to enable it, just run the following code.
EXEC sp_configure 'show advanced options' ,1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell' ,1;
GO
RECONFIGURE;
GO
In order to execute rename command we first need to enable XP_CMDSHELL if it is not already enabled.
EXEC xp_cmdshell 'RENAME "C:\SQL Server Data Files\MSSQL11\Data\VladTesting.mdf", "NewDatabaseName.mdf"'
GO
EXEC xp_cmdshell 'RENAME "C:\SQL Server Data Files\MSSQL11\Log\VladTesting_log.ldf", "NewDatabaseName_log.ldf"'
GO
CREATE DATABASE VladsAwesomeDB ON
( FILENAME = N'C:\SQL Server Data Files\MSSQL11\Data\VladsAwesomeDB.mdf' ),
( FILENAME = N'C:\SQL Server Data Files\MSSQL11\Log\VladsAwesomeDB_log.ldf' ) FOR ATTACH
GO
ALTER DATABASE VladsAwesomeDB SET MULTI_USER
GO
EXEC sp_configure 'xp_cmdshell' ,0;
GO
RECONFIGURE;
GO
EXEC sp_configure 'show advanced options' ,0;
GO
RECONFIGURE;
GO
So now you know how to rename database. Usually this should only be done when there is specific business reason to do so. If command sp_renamedb or ALTER DATABASE Modify Name is used, it does not rename physical or logical files which can cause issues later when someone tries to create new database with same name as last one or someone does restore of backup without changing options.
No comments :
Post a Comment