Home > Articles > Programming > Visual Basic

  • Print
  • + Share This

SQL Server to Access Database Table Export Program

Large companies tend to rely on many different types of databases, ranging in scale from a mainframe all the way down to a single-user database on an employee's PC. Frequently, new applications that require access to these databases appear, creating a complex web of dependencies between them. For example, a consultant may be hired to write an application that needs to read some data from an established SQL Server database. With ODBC, you can simply allow the consultant's application to attach to the database. However, this setup might pose a problem in certain situations:

  • The SQL Server administrator now has to maintain additional login information for the new application.

  • SQL Server performance may be negatively affected by the extra application.

  • Changing the SQL Server tables accessed by the new application may require changing the application code, which will be difficult after the consultant is long gone.

An easy answer to these problems is to build an export file on an automated basis for the new program to use. An Access database is an ideal format for this export file because the program can use it just as it would the SQL Server.

Building the Sample Program

In case you have not noticed, I like to rely on INI files a lot. There's a reason for this: They can make your program more useful. This result should be especially apparent in this example because the INI file contains all the information the program needs to perform the export operation. You can compile the program once and use several INI files for different exports. It is intended to be a command-line utility, and is executed like this:

MDBMAKE C:\Data\REVENUE.INI

MDBMAKE C:\Data\Employee.INI

The INI files themselves contain information that the program needs to connect to the SQL Server and create the Access tables. For example, entries specify the Access database (destination database) and the SQL Server connect string (source database):

DBFile=\\MYSERVER\PUBLIC\HRDATA\HRDATA.MDB

SQLConnect="ODBC:DATABASE=personnel:uid=fred:pwd=garvin:DSN=MYSQLDB"

Next, the [Tables] section specifies the name and number of tables you want to create:

[Tables]
Tables=4
Table1SQL=hrinfo
Table1MDB=hrinfo

Table1INI=hrinfo

Each table also contains a section that specifies the number and type of the fields in the table. For example, the hrinfo section might look like this:

[hrinfo]
Fields=2
Fd1Name="EmployeeID"
Fd1Type=DOUBLE
Fd2Name="Name"
Fd2Type=TEXT
Fd2Size=40

While executing, the program uses For loops to browse through each section in the INI file because it needs the field information. For example, the hrinfo table created by the program has two fields: EmployeeID, which is of type Double, and Name, which is a 40-character text field.

Understanding the Sample Program

The SQL export program has just a few generic functions and no real user interface (other than a progress screen). The important functions are as follows:

  • CreateLocalFile. Creates the database (MDB) file.

  • CreateTable. Creates an empty table in the database.

  • TransferTable. Transfers data from the SQL Server table to the new database.

  • Main. Controls the flow of the program.

These functions are shown in Listing 23.3. Following the listing is an explanation of what happens during a sample program run.

Listing 23.3  Transferring Information from SQL to Access

'Important variables:
Dim dbLocal As Database     'Destination database (Access)
Dim dbSQL As Database       'Source database (MS SQL Server)
Dim sDBLocalPath As String  'Path to destination database
Dim sINIPath As String      'Path to INI File

Sub Main()
    Dim sConnect As String      'SQL Server Connect String
    Dim nTables As Integer      'Number of tables to transfer
    Dim nCurTable As Integer    'Counter for current table
    Dim sSQLTable As String     'Name of the SQL table
    Dim sMDBTable As String     'Name of the Access table
    Dim sSection As String      'INI file [Section]
    Dim nCommand As Integer     'Commands can be run on the
    Dim sCommand As String      'Access database (i.e. create index)
        
    'GET INI FILE NAME
    sINIPath = App.Path & "\SQLXPORT.ini"
    If Trim$(Command$) <> "" Then sINIPath = Command$
    
    'READ INFO FROM THE INI FILE
    sDBLocalPath = sGetINIString(sINIPath, "General", "DBFile", "test.mdb")
    sConnect = sGetINIString(sINIPath, "General", "SQLConnect", "ODBC;")
    nTables = CInt(sGetINIString(sINIPath, "Tables", "Tables", "0"))
    
    'SHOW FORM AND CONNECT TO SQL SERVER
    frmWait.Show
    frmWait.lblWait = "Connecting to SQL Server..."
    DoEvents
    On Error GoTo MainError
    Set dbSQL = OpenDatabase("", False, True, sConnect)
        
    'CALL FUNCTION TO CREATE MDB FILE
    frmWait.lblWait = "Creating MDB file..."
    DoEvents
    CreateLocalFile
    DoEvents
    
    'CREATE TABLES IN THE NEW MDB FILE
    For nCurTable = 1 To nTables
        sSQLTable = sGetINIString(sINIPath, "tables", "table" & nCurTable & _
[ccc]                              "SQL", "none")
        sMDBTable = sGetINIString(sINIPath, "tables", "table" & nCurTable & _   
[ccc]                             "MDB", "none")
        sSection = sGetINIString(sINIPath, "tables", "table" & nCurTable & _ 
[ccc]                             "INI", "none")
        frmWait.lblWait = "Transferring " & sMDBTable
        TransferTable sSQLTable, sMDBTable, sSection
    Next nCurTable
                
    'THE DATABASE HAS BEEN CREATED, RUN COMMANDS ON IT IF NECESSARY
    nCommand = 0
    sCommand = ""
    While sCommand <> "?"
        If nCommand <> 0 Then dbLocal.Execute sCommand
        nCommand = nCommand + 1
        sCommand = sGetINIString(sINIPath, "General", "Command" & nCommand, "?")
    Wend
       
    'CLOSE EVERYTHING DOWN AND END
    frmWait.lblWait = "Disconnecting..."
    dbLocal.Close
    dbSQL.Close
    Unload frmWait
    DoEvents
    End

MainError:
    frmWait.Hide
    Screen.MousePointer = vbDefault
    WriteErrMsg "Main - Error " & Err & ": " & Error
    End
    Exit Sub

End Sub
Sub TransferTable(sSQLTable As String, sLocalTable As String, sSection As _ 
[ccc]            String)

'This function transfers data from SQL server to an Access table
    
    Dim rstemp As Recordset 'SQL recordset
    Dim aTable As Recordset 'Access table
    Dim nTemp As Integer    '  Counter
    Dim nFields As Integer  '  variables
    Dim nCount As Integer   '
    Dim sSQL As String      'SQL statement
    Dim sTemp As String
    

On Error GoTo TRTError:
    
    frmWait.ProgressBar1.Visible = True
    nCount = 0
    frmWait.ProgressBar1.Min = 0
    
    'The user can either transfer a SQL table as-is,
    'or the results of a query involving multiple tables.
    'This next IF statement determines which and sets up the
    'SQL statement- either "Select * from table" or the
    'user-defined SQL statement.
    
    sSQL = sGetINIString(sINIPath, sSection, "SQL", "")
    If sSQL = "" Then
        Set rstemp = dbSQL.OpenRecordset("Select Count(*) from " & sSQLTable, _ 
[ccc]                       dbOpenSnapshot, dbForwardOnly)
        frmWait.ProgressBar1.Max = CInt(Trim$(" 0" & rstemp.Fields(0)))
        rstemp.Close
        DoEvents
    Else
        nTemp = 2
        sTemp = sGetINIString(sINIPath, sSection, "SQL" & nTemp, "")
        While sTemp <> ""
            If sTemp <> "" Then sSQL = sSQL & sTemp
            nTemp = nTemp + 1
            sTemp = sGetINIString(sINIPath, sSection, "SQL" & nTemp, "")
        Wend
        frmWait.ProgressBar1.Max = 2000 'Set arbitrary value on progress bar
    End If
    
    
    'Actually open the recordset
    If sSQL = "" Then
        Set rstemp = dbSQL.OpenRecordset("Select * from " & sSQLTable, _ 
[ccc]                       dbOpenSnapshot, dbForwardOnly)
    Else
        Set rstemp = dbSQL.OpenRecordset(sSQL, dbOpenSnapshot, dbForwardOnly + _ 
[ccc]                       dbSQLPassThrough)
    End If
    
    'Open Local table
    Set aTable = dbLocal.OpenRecordset(sLocalTable, dbOpenTable)
    nFields = rstemp.Fields.Count - 1

    'Transfer each record
    While Not rstemp.EOF
        aTable.AddNew
        For nTemp = 0 To nFields
            aTable.Fields(nTemp) = rstemp.Fields(nTemp)
        Next nTemp
        rstemp.MoveNext
        nCount = nCount + 1
        frmWait.ProgressBar1.Value = nCount
        aTable.Update
    Wend
    rstemp.Close
    aTable.Close
    Exit Sub

TRTError:
    WriteErrMsg "TRT-Error " & Err & ": " & Error
    End
    Exit Sub

End Sub
Sub CreateTable(ByRef tbl As TableDef, sTableName As String, sINISection As _ 
[ccc]          String)
'This function creates an empty table in an Access database
    
    Dim nFields As Integer      'Number of Fields
    Dim Fd() As New Field       'Array of fields
    Dim nCurField As Integer    'Counter for current field
    Dim sTemp As String
       
 On Error GoTo CRTError:
 
    nFields = CInt(sGetINIString(sINIPath, sINISection, "Fields", "0"))
    If nFields = 0 Then Exit Sub
    ReDim Fd(1 To nFields)
   
    tbl.Name = sTableName
    
    For nCurField = 1 To nFields
        Fd(nCurField).Name = sGetINIString_
           (sINIPath, sINISection, "Fd" & nCurField & "Name", "ERROR" & _ 
[ccc]                      nCurField)
        sTemp = sGetINIString(sINIPath, sINISection, "Fd" & nCurField & "Type", _ 
[ccc]                      "TEXT")
        Select Case sTemp
            Case "DOUBLE"
            Fd(nCurField).Type = dbDouble
            Case "MEMO"
            Fd(nCurField).Type = dbMemo
            'VB4/5 only
            Fd(nCurField).AllowZeroLength = True
            Case "BYTE"
            Fd(nCurField).Type = dbByte
            Case "INTEGER"
            Fd(nCurField).Type = dbInteger
            Case "DATE"
            Fd(nCurField).Type = dbDate
            Fd(nCurField).Required = False
            
            Case Else 'Text
            Fd(nCurField).Type = dbText
            Fd(nCurField).Size = CInt(sGetINIString_
              (sINIPath, sINISection, "Fd" & nCurField & "Size", "50"))
            Fd(nCurField).AllowZeroLength = True
        End Select
    
       tbl.Fields.Append Fd(nCurField)
    Next nCurField
    Exit Sub
CRTError:
    WriteErrMsg "CRT-Error " & Err & ": " & Error
    End
    Exit Sub
End Sub
Sub CreateLocalFile()
'This procedure creates the MDB file itself
    Dim MainTable() As New TableDef
    Dim sTemp As String
    Dim nTables As Integer
    Dim nCurTable As Integer
    Dim sSQLTable As String
    Dim sMDBTable As String
    Dim sSection As String
    
On Error GoTo CRLError

    If bFileExists(sDBLocalPath) Then Kill sDBLocalPath
    Set dbLocal = CreateDatabase(sDBLocalPath, dbLangGeneral)

    nTables = CInt(sGetINIString(sINIPath, "Tables", "Tables", "0"))
    ReDim MainTable(1 To nTables)
    
    For nCurTable = 1 To nTables
        sSQLTable = sGetINIString(sINIPath, "tables", "table" & nCurTable & _ 
[ccc]                        "SQL", "none")
        sMDBTable = sGetINIString(sINIPath, "tables", "table" & nCurTable & _ 
[ccc]                        "MDB", "none")
        sSection = sGetINIString(sINIPath, "tables", "table" & nCurTable & _ 
[ccc]                        "INI", "none")
        CreateTable MainTable(nCurTable), sMDBTable, sSection
        dbLocal.TableDefs.Append MainTable(nCurTable)
    Next nCurTable
    Exit Sub

CRLError:
    WriteErrMsg "CRL-Error " & Err & ": " & Error
    End
    Exit Sub
End Sub
Private Sub WriteErrMsg(sMessage As String)
    'Should an error occur, this function writes it to
    'another INI file. I did it this way because the
    'program runs as a scheduled process on a remote
    'machine, so no one would be there to answer an error
    'dialog. There is a second VB program that continuously
    'checks the Error.ini file and pages me with the error message.
        
    Dim sErrorINI As String
    sErrorINI = sGetINIString(sINIPath, "General", "ErrorINI", "error.ini")
    writeINIString sErrorINI, "Error", "Message", sMessage
    writeINIString sErrorINI, "Error", "Error", "True"
End Sub

First, the CreateLocalFile function gets the filename from the Dbpath= INI entry and uses Visual Basic's CreateDatabase function to create the new (and empty MDB) file. Next, the program uses a For loop to read through each table in the [Tables] section, repeatedly calling the CreateTable procedure. The CreateTable procedure, in turn, loops through the fields in the [tablename] section of the INI file, creating fields in the new table.

After a table is created, the TransferTable procedure takes care of transferring the data from an SQL Server table to one of the new tables. The procedure first creates a recordset from the SQL Server table and then loops through each record in the recordset, transferring the value for each field to the new table. During this process, users see a progress bar, as shown in Figure 23.4, to let them know something is happening.

Figure 23.4

The SQL data export program displays a progress bar while in action.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.