A community member has associated this post with a similar question:
I STILL can't find the right SQL syntax to COPY my database!

Only moderators can edit this content.

How do I, given a database's catalog name and/or physical mdf/log file names, determine and differentiate the LOGICAL file names of the database?

Robert Gustafson 606 Reputation points
2022-05-25T04:05:34.57+00:00

WHAT I HAVE:
Visual Basic 2019, Entity Framework 6+, SQL Server (version unsure), WinForms, .NET Framework 4.6+

MY PROBLEM:

In order to properly copy a database, while properly setting the catalog and file names for the copied version, I need to determine the logical file names for the mdf file(s) and the log file(s), and to tell which is for which. I start by specifying catalog name and mdf file name for the original database, while also specifying the catalog/file names for the copy.

I am told that one queries sys.database_files for the logical file names of the "current database". How do I ensure that sys.database_files knows which database is current, and figure out which logical files are for data (mdf) vs. log? My EF-driven code--which currently uses context.ExecuteSQL to initiate BACKUP and RESTORE SQL--depends on all this!

Please give me an answer ASAP, and in VB.NET/EF, and keep it as simple as possible.

My existing code is as follows (mind you, it makes naive assumptions at present about the logical file names):

''' <summary>
''' copy one database to another
''' </summary>
''' <param name="SourceCatalogName">catalog name of source database</param>
''' <param name="SourceFileName">file name of source database</param>
''' <param name="DestinationCatalogName">catalog name of destination database</param>
''' <param name="DestinationFileName">file name of destination database</param>
''' <returns>True if successful, False if cancelled</returns>
''' <remarks>Note the following:<br></br>
''' 1. If either database is the same as the currently open one (if any), if the
'''    source database doesn't exist, or if an error occurs while making the copy,
'''    an exception is thrown<br></br>
''' 2. If a database with the given destination catalog name and/or a file with the
'''    same name as the desination primary file name already exists, then the
'''    CatlogExists and/or DatabaseFileExists events will be fired to allow the user to
'''    decide whether to cancel the operation or overwrite the catalog and/or file with
'''    the database copy</remarks>
Public Overridable Function Copy(ByVal SourceCatalogName As String, _
    ByVal SourceFileName As String, _
    ByVal DestinationCatalogName As String, ByVal DestinationFileName As String) As Boolean
    '   normalize names for and verify existence of source database
    CheckNamesForOpenExisting(SourceCatalogName, SourceFileName)
    '   normalize names for destination database
    CheckNamesForCreateNew(DestinationCatalogName, DestinationFileName)
    '   see if either database is already opened
    VerifyIsNotOpen(SourceCatalogName, SourceFileName)
    VerifyIsNotOpen(DestinationCatalogName, DestinationFileName)
    '   verify existence of source database
    Using Context As SocialContactsTracker1 = _
            GetContextForExistingDatabase(SourceCatalogName, SourceFileName)
        '   do nothing
    End Using
    '   see if we need to overwrite destination database
    Using Context As SocialContactsTracker1 = _
            GetContextForNewDatabase(DestinationCatalogName, DestinationFileName)
        If Context Is Nothing Then
            '   exit if destination database exists and is not to be overwritten
            Return False
        End If
    End Using
    '   copy database using backup and restore
    Using Context As SocialContactsTracker1 = GetPrototypeContext()
        Dim BackupFileName As String = _
            SourceFileName.Substring(0, SourceFileName.Length - 3) & "bak"
        Dim BackupDeviceName As String = _
            SourceCatalogName.Substring(0, SourceCatalogName.Length - 5) & "_TEMP"
        '   perform copy using backup and restore
        With Context.Database
            .ExecuteSqlCommand(Entity.TransactionalBehavior.DoNotEnsureTransaction, _
                "BACKUP DATABASE """ & SourceCatalogName _
                    & """ TO DISK='" & BackupFileName & "'; " _
                & "RESTORE FILELISTONLY FROM DISK='" &  BackupFileName & "'; " _
                & "RESTORE DATABASE """ & DestinationCatalogName _
                    & """ FROM DISK='" & BackupFileName _
                        & "' WITH MOVE '" & SourceCatalogName & "_Data' TO '" _
                        & DestinationFileName & "', " _
                    & "MOVE '" & SourceCatalogName & "_Log' TO '" _
                        & IO.Path.ChangeExtension(DestinationFileName, Nothing) & "_log.ldf'; ")
        End With
        If IO.File.Exists(BackupFileName) Then
            '   remove temporary backup file
            IO.File.Delete(BackupFileName)
        End If
    End Using
    '   flag operation successful
    Return True
End Function

What specifically should be added/removed/changed to make this work?

PS. What instructions do I need to move/rename, rather than copy, a database and its catalog/files?

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,838 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,415 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,126 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,558 questions
{count} votes