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



我刚刚在新公司继承了一个数据库。 旧的数据库所有者没有留下任何好的文档和查询,很难跟踪。 寻找编程答案以跟踪每个查询中的字段源(它来自哪个表)。 更喜欢可以导出到Excel进行研究的东西,访问可视化是不好的。 我熟悉VBA。

这很混乱,但可以节省您收集每个查询的 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

我已经通过许多继承的数据库经历了这种情况。 我发现创建一个包含字段和它们来自的表/查询的 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

最新更新