我必须使用许多宏查询来记录MS Access数据库等。我希望使用代码将每个SQL查询提取到一个名称与查询相同的文件,例如,如果查询名为q_warehouse_issues,那么我希望提取SQL到名为q_warehouse_issues.sql的文件
我不希望导出QUERY结果集,只是SQL!
我知道我可以在Access中手动执行此操作,但我厌倦了所有点击,执行saveas等。
这应该让你开始:
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDB()
For Each qdf In db.QueryDefs
Debug.Print qdf.SQL
Next qdf
Set qdf = Nothing
Set db = Nothing
您可以使用文件系统对象或内置的VBA文件I / O功能将SQL写入文件。我假设您要求的更多关于如何获取SQL而不是关于如何写出文件,但是如果您需要,请在评论中这样说,我将编辑帖子(或者有人会发布他们自己的答案说明)。
希望这可以帮助。
Public Function query_print()
Dim db As Database
Dim qr As QueryDef
Set db = CurrentDb
For Each qr In db.QueryDefs
TextOut (qr.Name)
TextOut (qr.SQL)
TextOut (String(100, "-"))
Next
End Function
Public Sub TextOut(OutputString As String)
Dim fh As Long
fh = FreeFile
Open "c:\File.txt" For Append As fh
Print #fh, OutputString
Close fh
End Sub
此解决方案包括查询中的字段
Public Sub ListQueries()
' Author: Date: Contact:
' André Bernardes 09/09/2010 08:45 [email protected] http://al-bernardes.sites.uol.com.br/
' Lista todas as queries da aplicação.
' Listening:
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
On Error Resume Next
For i = 0 To CurrentDb.QueryDefs.Count - 1
Debug.Print "Query: " & CurrentDb.QueryDefs(i).Name
For j = 0 To CurrentDb.QueryDefs(i).Fields.Count - 1
Debug.Print "Field " & CurrentDb.QueryDefs(i).Fields(j).Name
Next
Debug.Print " SQL: " & CurrentDb.QueryDefs(i).SQL
Next
End Sub
Tools->References....
Microsoft Scripting Runtime
。然后,此代码将查询导出到适合使用grep的文件:
Sub ExportQueries()
Dim fso As New FileSystemObject
Dim stream As TextStream
Set stream = fso.CreateTextFile("e:\temp\queries.txt")
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb()
For Each qdf In db.QueryDefs
stream.writeline "Name: " & qdf.Name
stream.writeline qdf.SQL
stream.writeline "--------------------------"
Next qdf
Set qdf = Nothing
Set db = Nothing
End Sub
我修改了@ andre-bernardes的代码以使用“|”查询名称之前的分隔符和SQL语句之前的“:”分隔符。使用不同的分隔符可以更容易地使用python解析Queries.txt
文件,并创建查询和SQL语句的字典。然后,您可以使用此字典在SQLite表中创建视图。
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
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}
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)