Home > Articles > Programming > Visual Basic

Master's Toolbox

  • 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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020