Export all MS Access SQL queries to text files

后端 未结 5 1531
失恋的感觉
失恋的感觉 2020-12-08 07:32

I have to document an MS Access database with many many macros queries, etc. I wish to use code to extract each SQL query to a file which is named the same as the query, eg

5条回答
  •  盖世英雄少女心
    2020-12-08 07:55

    I modified @andre-bernardes's code to use "|" separators before the query names and ":" separators before the SQL statements. The different separators make it easier to parse the Queries.txt file with python and create a dictionnary of queries and SQL statements. You can then use this dictionary to create views in an SQLite table for example.

    VBA code to extract the SQL queries

    Public Sub ListQueries()
        ' Modified from André Bernardes
        Dim i As Integer
        Dim ff As Long
        ff = FreeFile()
        Open "C:\Dev\Queries.txt" For Output As #ff
        On Error Resume Next
    
        For i = 0 To CurrentDb.QueryDefs.Count - 1
            Debug.Print "|" & CurrentDb.QueryDefs(i).Name & ":"
            Print #ff, "|" & CurrentDb.QueryDefs(i).Name & ":"
    
            Debug.Print CurrentDb.QueryDefs(i).SQL
            Print #ff, CurrentDb.QueryDefs(i).SQL
        Next
    End Sub
    

    Python code to parse Queries.txt into a dictionary

    queries_file = open(data_path + '/Queries.txt')
    queries = queries_file.read().split('|')
    l = [x.split(':') for x in queries]
    l.pop(0)
    table_name_to_query = {name: query for name, query in l}
    

    Create SQLite views from the Access queries

    import sqlite3
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    for table, query in table_name_to_query.items():
        try:
            c.execute("CREATE VIEW `%s` AS %s" % (table,query))
            print("\n\n"+ table + " passed")
            print(query)
        except Exception as e:
            print("\n\n"+ table + " error")
            print(e)
            print(query)
    

提交回复
热议问题