继承的MS Access数据库,跟踪查询源

时间:2017-10-31 18:21:41

标签: vba ms-access

我刚在新公司继承了一个数据库。旧数据库所有者没有留下任何好的文档和查询非常难以跟踪。寻找程序化的答案来跟踪每个查询中的字段来源(它来自哪个表)。首选某些东西可以导出到Excel学习,Access可视化并不好。熟悉VBA。

2 个答案:

答案 0 :(得分:1)

这非常混乱,但可以节省您收集每个查询的SQL代码的时间。以下代码将QueryDefs集合中存储的所有SQL导出到文本文件中。我让它用空格分隔符拆分代码,但逗号可能更好。数据不会被标准化,我没有时间去达到这种复杂程度。只需确保在执行前更新strPath。希望这会有所帮助。

Sub PullQuerySQL()

    Dim dbs As Database
    Dim i As Integer
    Dim fso As Object
    Dim oFile As Object
    Dim varParse() As String
    Dim element As Variant
    Dim strPath As String

    strPath = ".txt"

    Set dbs = CurrentDb()
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile(strPath)

    For i = 0 To dbs.QueryDefs.Count - 1
        oFile.WriteLine dbs.QueryDefs(i).Name
        varParse = Split(dbs.QueryDefs(i).SQL, " ")
        For Each element In varParse
            oFile.WriteLine element
        Next element
    Next i

    oFile.Close

    Set oFile = Nothing
    Set fso = Nothing
    Set dbs = Nothing

End Sub

答案 1 :(得分:0)

我使用了很多继承的数据库。我发现创建一个包含字段和它们来自的表/查询的Access表非常有用。请尝试以下代码。当我调用它时,它会提示您查找要“映射”的查询的名称。然后它将创建一个名为“queryName Definitions”的新表。

Option Compare Database

Public Sub MapQuery()

 Dim strQueryName As String
 Dim rst As DAO.Recordset
 Dim fld As Field
 Dim strSource As String
 Dim strField As String
 Dim strValue As String
 Dim strSQL1 As String
 Dim strSQL2 As String
 Dim booExists As Boolean


strQueryName = InputBox("Please enter the name of the query that you are looking to map")

   Set rst = CurrentDb.OpenRecordset(strQueryName)

On Error GoTo error1
    booExists = IsObject(CurrentDb.TableDefs(strQueryName & " Definitions"))
    DoCmd.DeleteObject acTable, strQueryName & " Definitions"
continue:
    strSQL1 = "CREATE TABLE [" & strQueryName & " Definitions]" & " (FieldName CHAR, SourceName CHAR);"
    DoCmd.RunSQL (strSQL1)
    DoCmd.SetWarnings False
    For Each fld In rst.Fields

    strField = fld.Name
    strSource = fld.SourceTable


Debug.Print strValue

    strSQL2 = "INSERT INTO [" & strQueryName & " Definitions]" & "(FieldName, SourceName) VALUES(""" & strField & """, """ & strSource & """);"

    DoCmd.RunSQL (strSQL2)
    Next fld

error1:
    If Err.Number = 3265 Then
        Resume continue
    Else
    MsgBox Err.Description

    End If

    DoCmd.SetWarnings True
    Exit Sub

    DoCmd.SetWarnings True
End Sub