The method of modifying SQL Server database logical name, database name and physical name by T-SQL statement

Time:2020-3-24

In this paper, the method of modifying SQL Server database logical name, database name and physical name by T-SQL statement is introduced. To share with you for your reference, as follows:

Changing the writing method of physical file name sql statement of MSSQL database

Note: in the activity monitor, make sure that no process is connected to the database you want to rename!!!!!!!!!!!!!!!!!!!!

SQL statement is as follows

USE master
--Change logical name
ALTER DATABASE YQBlog MODIFY FILE(NAME='YQBlogAA',NEWNAME='YQBlog')
-- GO
ALTER DATABASE YQBlog MODIFY FILE(NAME='YQBlogAA_log',NEWNAME='YQBlog_log')
-- GO
--Change database name
EXEC sys.sp_renamedb @dbname = 'YQBlogAA', -- sysname
  @newname = 'YQBlog'
  GO
--Detach database
EXEC sp_detach_db YQBlog
GO
--Open XP ﹣ cmdshell function
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
------ change the physical name (Note: no Chinese in the path)
EXEC xp_cmdshell 'ren C:\Users\Administrator\Desktop\YQBlogAA.mdf YQBlog.mdf'
------ change physical name
EXEC xp_cmdshell 'ren C:\Users\Administrator\Desktop\YQBlogAA_log.ldf YQBlog_log.ldf'
--GO
------ reattach
EXEC sp_attach_db @dbname = N'YQBlog',
  @filename1 = N'C:\Users\Administrator\Desktop\YQBlog.mdf',
  @filename2 = N'C:\Users\Administrator\Desktop\YQBlog_log.ldf'

For more information about SQL server, please refer to the following topics: SQL server stored procedure skills, SQL server query operation skills, SQL Server index operation skills, SQL Server paging technology summary and SQL Server common functions summary

I hope that this article will be helpful to the SQL Server database programming.