3

我正在尝试创建一个 Access 数据库,它将多个结构相同的数据库链接在一起。这些其他数据库是从具有相同表的 3D 模型导出的,但每个数据库中的数据不同。我需要做的是从所有数据库中报告,就像它们是一个大数据库一样。我认为我会如何处理这个问题是创建查询,将每个数据库中的单个相同表合并为一个查询,然后我可以在所有其他报告中使用它。我编写的将表格连接在一起的代码如下。我遇到的麻烦是,这段代码在“Set QueryDef ...”行上给了我一个堆栈空间不足的错误。有人可以告诉我我做错了什么吗?

Public Sub CreateUnionQueries()
'On Error GoTo Err_CreateUnionQueries
Dim QueryRs As DAO.Recordset
Dim TableRs As DAO.Recordset
Dim QueryDef As DAO.QueryDef
Dim SQLText As String
Dim qry As QueryDef

'Get list of all Foreign Table Names
Set QueryRs = CurrentDb.OpenRecordset("select distinct ForeignName from msysobjects where ForeignName is not null")

'Loop over list to create union queries
If QueryRs.RecordCount <> 0 Then
    Do While Not QueryRs.EOF
        Set TableRs = CurrentDb.OpenRecordset("select Name from msysobjects where ForeignName = """ & QueryRs![ForeignName] & """")
        Do While Not TableRs.EOF
            SQLText = SQLText & "select * from " & TableRs![Name]
            TableRs.MoveNext
            If Not TableRs.EOF Then
                SQLText = SQLText & " UNION ALL "
            End If
        Loop
        'Create union query
        For Each qry In CurrentDb.QueryDefs
            If qry.Name = "Q-" & QueryRs![ForeignName] Then
               DoCmd.DeleteObject acQuery, "Q-" & QueryRs![ForeignName]
            End If
        Next qry
        Set QueryDef = CurrentDb.CreateQueryDef("Q-" & QueryRs![ForeignName], SQLText)
        QueryDef.Close
        Set QueryDef = Nothing
        QueryRs.MoveNext
        TableRs.Close
        Set TableRs = Nothing
    Loop
Else
    MsgBox "No files are linked currently"
End If

QueryRs.Close

Err_CreateUnionQueries:
    MsgBox "We have an error"
    Set QueryRs = Nothing
    Set TableRs = Nothing
    Exit Sub
End Sub
4

1 回答 1

0

哦,伙计,我是个白痴。发现了问题。当我循环时,我没有将 SQLText 设置回空,所以它将我对表组的查询附加到最后一个。删除了它,现在它按预期工作。谢谢你们的帮助。

于 2012-10-03T15:04:40.230 回答