我需要创建涉及某种UNION的多个查询。我能够弄清楚的唯一方法是在下面。有什么方法可以简化流程,所以我不需要为每个表单独使用一个工会吗? (我有大约50个表,并且不想为每个表执行此操作) - 使用Access数据库
SELECT Header1,Header2,header 3,header 4
FROM score_ADACOMPT
UNION
SELECT Header1,Header2,header 3,header 4
FROM score_ADADESG
UNION
SELECT Header1,Header2,header 3,header 4
来自Score_API
UNION
SELECT Header1,Header2,header 3,header 4
来自score_COMPCAC
UNION
SELECT Header1,Header2,header 3,header 4
来自Score_CRV
UNION
答案 0 :(得分:1)
我认为你会遇到这种方法的一些障碍。我从来没有找到关于它的官方文档,但Access一次只能处理这么多的UNION操作。它似乎取决于操作和查询的复杂程度。您可以尝试编写VBA来创建UNION查询语法,并查看Access是否可以处理它。如果是的话,那就认为自己很幸运。
或者,您可以考虑创建一个表来保存这些值,然后运行追加查询以将数据加载到该表中。这有利有弊,具体取决于应用程序环境,以及您计划在数据组合后对数据进行的操作。
循环访问DAO TableDefs和创建UNION查询的示例:
Public Sub TestIt()
BuildUNIONQuery "UNIONTest"
End Sub
Public Sub BuildUNIONQuery(saveQueryName As String)
'builds a large union query for queries starting with "score_" and contains fields: Header1, Header2, header 3, header 4
Dim qryStr As String
Dim tDef As DAO.TableDef
Dim qDef As DAO.QueryDef
Dim db As DAO.Database
Set db = Access.CurrentDb
qryStr = ""
For Each tDef In db.TableDefs
If tDef.Name Like "score_*" Then
qryStr = qryStr & "SELECT [Header 1], [Header 2], [header 3], [header 4] "
qryStr = qryStr & "FROM [" & tDef.Name & "] "
qryStr = qryStr & "UNION "
End If
Next tDef
'remove last UNION from string
If Len(qryStr) > 0 Then
qryStr = Left(qryStr, Len(qryStr) - 6)
End If
If QueryExists(saveQueryName) Then 'query exits update SQL for current item
Set qDef = db.QueryDefs(saveQueryName)
qDef.SQL = qryStr
db.QueryDefs.Refresh
Else
Set qDef = db.CreateQueryDef(saveQueryName, qryStr)
db.QueryDefs.Refresh
End If
End Sub
Public Function QueryExists(qName As String) As Boolean
'determine if query name already exists in the database
Dim qDef As DAO.QueryDef
Dim db As DAO.Database
Set db = Access.CurrentDb
QueryExists = False
For Each qDef In db.QueryDefs
If qDef.Name = qName Then
QueryExists = True
Exit Function
End If
Next qDef
结束功能