Changing the name of a SQL database

前端 未结 4 755
北恋
北恋 2021-02-06 04:21

What is the correct procedure to rename a database?

Example: I have a database that I can access with SQL Server Management Studio and has a name like \"MyDatabase\". Ph

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 05:09

    Be careful when you use Rename option from context menu that appear when you right click on the database in Management Studio. This option does not change the database file names. To change logical filenames for DATA and LOG files you can also use a Management Studio interface but unfortunately sometimes it does not work.

    Let’s do it properly... it should works always.

    1. Detach database: Using Management Studio, right-click on database > go to “Tasks” > “Detach”, click OK to detach a database (note: that the DB can not be used to detach it)
    2. Rename Physical files: Once the database is detached the physical files are unlocked and you can rename them using Windows Explorer: enter image description here
    3. Attaching database with New Name: For it use T SQL:

      USE [master] CREATE DATABASE [SqlAndMe] ON ( FILENAME = N’C:\…\NewName.mdf’), ( FILENAME = N’C:\…\NewName_log.LDF’) FOR ATTACH

    4. Rename Logical file names: Execute this T SQL:

      USE [NewName] ALTER DATABASE [NewName] MODIFY FILE (NAME=N’OldName’, NEWNAME=N’NewName’) ALTER DATABASE [NewName] MODIFY FILE (NAME=N’OldName_log’, NEWNAME=N’NewName_log’) SELECT name, physical_name FROM [NewName].sys.database_files

    It should works!

提交回复
热议问题