What's the best (and simplest way) to MOVE an SQL Server database file?

Robert Gustafson 606 Reputation points
2023-08-11T01:24:54.11+00:00

WHAT I HAVE:

Visual Basic 2019, WinForms, .NET Framework 4.0+, Entity Framework 6.0+, SQL Server

MY ISSUE:

I'm writing a desktop app that uses Entity Framework to manage multiple databases (with user-specified catalog-name/mdf-file-name combinations) using the same schema. I already know the SQL needed to copy a database from 1 catalog/database-file to another, but I need to know that best way to do a move. Currently, I simply copy the database, then delete the original--but that requires setting up a second catalog and having enough space on disk for both database files, even though only 1 will ultimately remain. I've heard that the SQL code for simply moving the mdf file (and its ldf file) is more involved than the SQL for doing a copy. But suppose I have a database identified with CatalogName and FileAndPathName1.mdf, and I want to move (as opposed to copy-and-delete) the mdf file to FileAndPathName2.mdf while keeping the catalog. What does that entail in terms of SQL code? (Assume that I also want to move the ldf file from FileAndPathName1.ldf to FileAndPathName2.ldf.)

Please answer ASAP in VB.NET/SQL Server code, as make it as simple as possible.

Developer technologies | Windows Forms
Developer technologies | .NET | Other
Developer technologies | VB
SQL Server | Other
{count} votes

7 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2023-08-11T01:49:32.3266667+00:00

    If you just want to move the data and log file with possible rename, you just

    • Put database in single user mode
    • take the database offline via alter database set offline
    • rename physical files
    • change names in Sqlserver via alter database modify file
    • take database online again with alter database
    • Put database back to multi user.
    1 person found this answer helpful.

  2. Olaf Helper 47,441 Reputation points
    2023-08-11T08:49:06.3933333+00:00

    I need to know that best way to do a move.

    Easiest is: Backup & restore under a new name, see Copy Databases with Backup and Restore


  3. Vinicius Climaco 0 Reputation points MVP
    2023-08-11T11:51:20.1366667+00:00

    Hello!!! Here is the code you requested in C#.

    Remember to replace the source_server_name, source_database_name, destination_server_name and destination_database_name values with the appropriate names of the servers and databases involved in the migration.

    If my answer has helped in any way, I ask you to like and report.

    Thank you and good luck!

    Note: Make sure you have the SMO libraries installed in your project.

    using System;
    using Microsoft.SqlServer.Management.Smo;
    
    namespace DatabaseMigration
    {
        class Program
        {
            static void Main(string[] args)
            {
                string sourceServerName = "source_server_name";
                string sourceDatabaseName = "source_database_name";
                string destinationServerName = "destination_server_name";
                string destinationDatabaseName = "destination_database_name";
    
                string sourceConnectionString = $"Data Source={sourceServerName};Integrated Security=True;";
                string destinationConnectionString = $"Data Source={destinationServerName};Integrated Security=True;";
    
                try
                {
                    // Connect to the source server and database
                    Server sourceServer = new Server(new ServerConnection(sourceConnectionString));
                    Database sourceDatabase = sourceServer.Databases[sourceDatabaseName];
    
                    // Create a backup of the source database
                    Backup backup = new Backup();
                    backup.Action = BackupActionType.Database;
                    backup.Database = sourceDatabaseName;
                    backup.Devices.AddDevice("backup.bak", DeviceType.File);
                    backup.Initialize = true;
                    backup.SqlBackup(sourceServer);
    
                    // Connect to the destination server
                    Server destinationServer = new Server(new ServerConnection(destinationConnectionString));
                    
                    // Restore the backup to the destination server and database
                    Restore restore = new Restore();
                    restore.Action = RestoreActionType.Database;
                    restore.Database = destinationDatabaseName;
                    restore.Devices.AddDevice("backup.bak", DeviceType.File);
                    restore.ReplaceDatabase = true;
                    restore.SqlRestore(destinationServer);
    
                    Console.WriteLine("Database migration completed successfully.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred: " + ex.Message);
                }
            }
        }
    }
    
    

  4. Javier Villegas 905 Reputation points MVP
    2023-08-11T16:40:44.8033333+00:00

    Hello

    if by MOVE database file you mean move a MDF or LDF file from one drive/folder to another the easiest way to to detach the database , move the file(s) to new location and finally attach it

    Here is all the info

    Database Detach and Attach (SQL Server)


  5. Robert Gustafson 606 Reputation points
    2023-08-11T18:37:34.95+00:00

    Will this work for the detach/move/attach approach?

    1> Execute the following SQL against the master database (I'll be using SqlCommand with an SQLConnection to "master" in my VB.NET code to do all SQL):

    EXEC sp_detach_db @dbname = N'CatalogName';

    2> Then MOVE the underlying "OldPathName\OldDatabaseFileName.mdf" and "OldPathName\OldLogFileName.ldf" files to "NewPathName\NewDatabaseFileName.mdf" and "NewPathName\NewLogFileName.ldf", respectively, with 2 standard File.Move statements

    3> Then do this against the master:

    CREATE DATABASE CatalogName ON (FILENAME = 'NewPathName\NewDatabaseFileName.mdf'), (FILENAME = 'NewPathName\NewLogFileName.ldf') FOR ATTACH;

    Finally, is this the most reliable way to move the mdf and log files while keeping them associated with the same catalog? Or is Bruce's (SQLWorks.com) approach more reliable? If the latter, then what's the SQL/VB.NET code needed for that approach?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.