How to Generate SQL Dump Scripts (CREATE/INSERT) from Microsoft Access Tables Programmatically


4 views

When migrating from Microsoft Access to more robust database systems like MySQL or PostgreSQL, developers often need to extract table structures and data as SQL scripts. While Access doesn't natively support SQL dump functionality like MySQL's mysqldump, we can achieve this through various methods.

The simplest approach is using Access' export wizard:

1. Right-click the table in Access
2. Select "Export" > "ODBC Database"
3. Choose "Save export steps" and specify SQL file

However, this method has limitations in customization and bulk operations.

For more control, use VBA to generate SQL scripts:

Public Sub GenerateSQLDump()
    Dim db As Database
    Dim tdf As TableDef
    Dim fld As Field
    Dim strSQL As String
    
    Set db = CurrentDb()
    
    For Each tdf In db.TableDefs
        If Left(tdf.Name, 4) <> "MSys" Then
            ' Generate CREATE TABLE statement
            strSQL = "CREATE TABLE " & tdf.Name & " ("
            For Each fld In tdf.Fields
                strSQL = strSQL & fld.Name & " " & _
                GetSQLType(fld.Type) & ", "
            Next
            strSQL = Left(strSQL, Len(strSQL) - 2) & ");"
            
            Debug.Print strSQL
            ' Generate INSERT statements would follow similar logic
        End If
    Next
End Sub

Function GetSQLType(accessType As Integer) As String
    ' Map Access data types to SQL standard types
    Select Case accessType
        Case dbText: GetSQLType = "VARCHAR(255)"
        Case dbLong: GetSQLType = "INT"
        ' Add other type mappings as needed
    End Select
End Function

Several third-party tools can convert Access databases to SQL:

  • AccessToMySQL (Windows GUI tool)
  • mdbtools (Linux/Unix command line)
  • SSMA (Microsoft SQL Server Migration Assistant)

For advanced scenarios like:

  • BLOBs and binary data
  • AutoNumber/identity fields
  • Table relationships and constraints

Consider using a hybrid approach combining VBA for schema extraction and CSV exports for data, then transforming with scripting languages like Python.

When dealing with large tables:

  • Batch INSERT statements (100-1000 rows per statement)
  • Disable indexes during import
  • Use transactions for better performance

Here's a Python snippet using pyodbc for partial extraction:

import pyodbc
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path/to/db.accdb;')
cursor = conn.cursor()

# Get table list
tables = cursor.tables(tableType='TABLE')
for table in tables:
    table_name = table.table_name
    if not table_name.startswith('MSys'):
        print(f"CREATE TABLE {table_name} (")
        # Get columns would follow similar logic

For one-time migrations, GUI tools might suffice. For repeated or automated processes, develop custom scripts using the approaches above. Always validate the generated SQL against your target database system's syntax requirements.


When migrating from Microsoft Access to more robust database systems like MySQL or PostgreSQL, developers often need to extract table schemas and data as SQL scripts. Access doesn't natively provide this functionality, but several technical approaches exist to accomplish this conversion.

Access can export data to text files which can then be converted:


1. Right-click the table in Access
2. Select Export > Text File
3. Choose delimiter options
4. Use a script to convert the CSV to INSERT statements

This provides the most control over output format:


Public Sub GenerateSQL()
Dim tbl As TableDef
Dim fld As Field
Dim db As Database
Dim sql As String

Set db = CurrentDb()

For Each tbl In db.TableDefs
If Left(tbl.Name, 4) <> "MSys" Then
sql = "CREATE TABLE " & tbl.Name & " ("

For Each fld In tbl.Fields
sql = sql & fld.Name & " " & GetSQLType(fld.Type) & ", "
Next

sql = Left(sql, Len(sql) - 2) & ");"
Debug.Print sql
End If
Next
End Sub

Function GetSQLType(accessType As Integer) As String
Select Case accessType
Case dbText: GetSQLType = "VARCHAR(255)"
Case dbInteger: GetSQLType = "INT"
Case dbLong: GetSQLType = "BIGINT"
Case Else: GetSQLType = "TEXT"
End Select
End Function

Several commercial tools like EMS Database Comparer or AccessToMySQL can automate this process with schema mapping capabilities:

  • Preserves primary keys and indexes
  • Handles complex data types automatically
  • Batch processes multiple tables

For INSERT statements, consider using this VBA approach:


Public Sub ExportDataAsINSERTS()
Dim rs As Recordset
Dim f As Field
Dim sql As String
Dim i As Integer

Set rs = CurrentDb.OpenRecordset("SELECT * FROM Customers")

Do Until rs.EOF
sql = "INSERT INTO Customers ("

For Each f In rs.Fields
sql = sql & f.Name & ", "
Next

sql = Left(sql, Len(sql) - 2) & ") VALUES ("

For i = 0 To rs.Fields.Count - 1
If IsNull(rs.Fields(i).Value) Then
sql = sql & "NULL, "
Else
sql = sql & "'" & Replace(rs.Fields(i).Value, "'", "''") & "', "
End If
Next

sql = Left(sql, Len(sql) - 2) & ");"
Debug.Print sql
rs.MoveNext
Loop
End Sub

  • Access' auto-number fields require special handling in target databases
  • Date/Time formats often need conversion
  • MEMO fields might exceed some databases' text limits
  • OLE Object fields typically need alternative storage approaches

For databases with many tables, combine schema and data export in a batch process:


Public Sub ExportFullDatabase()
Dim tbl As TableDef
Dim db As Database

Set db = CurrentDb()

For Each tbl In db.TableDefs
If Not tbl.Name Like "MSys*" Then
ExportTableSchema tbl
ExportTableData tbl
End If
Next
End Sub