18 May 2017

Create SQL DB Attach script

Function CreateAttachScript() As String

    Dim template As String = "
PRINT '** {0}'
CREATE DATABASE [{1}] ON 
    ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\{2}' ),
    ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA\{3}' )
 FOR ATTACH
GO
"

    Dim ele As New Dictionary(Of String, String)

    With ele
        .Add("ZZ_Export.mdf", "ZZ_Export_log.ldf")
        .Add("ZZ_Storico.mdf", "ZZ_Storico_log.ldf")
        ' add here other files...
    End With


    Dim s As New System.Text.StringBuilder("USE [master]
GO
")

    Dim dbName As String = ""

    For Each db As KeyValuePair(Of String, String) In ele
        dbName = db.Key.Replace(".mdf", "").Replace(".ldf", "").Replace(".MDF", "").Replace(".LDF", "")

        If dbName <> "" Then
        s.AppendFormat(template, dbName, dbName, db.Key, db.Value)
        End If
    Next

    Return s.ToString

End Function