我在Access中有各种具有相同字段的表,我想将它们合并到一个表中。唯一的问题是,当我导入它们时,它们都有不同的名称-它们唯一的共同之处是 USR02 。我创建了一个空表,其中包含名为USR_02_ALL的所需列。但是,我不能用该表中的数据填充它。我正在使用Access2016。到目前为止(从某人获得)的代码是:
Sub Buildquery()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim sqlFinal As String
Dim sql1 As String
On Error GoTo Buildquery_Error
sql1 = "SELECT * INTO USR_02_ALL FROM ( " & vbCrLf
Dim sql2 As String
sql2 = "SELECT * FROM "
Dim sql3 As String
sql3 = "UNION ALL "
Set db = CurrentDb
sqlFinal = sql1
For Each tdf In db.TableDefs
If tdf.Name Like "*" & "USR02" & "*" Then
sqlFinal = sqlFinal & tdf.Name & " " & sql3 & sql2 & tdf.Name & vbCrLf
End If
Next tdf
Debug.Print sqlFinal 'You can put this wherever you want
On Error GoTo 0
Exit Sub
Buildquery_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Buildquery of Module AWF_Related"
End Sub
答案 0 :(得分:0)
命令SELECT * INTO USR_02_ALL FROM...
将创建一个新表,该表具有与查询结果相同的字段。当您编写“我已经创建了一个空表...”时,此语句将失败,并显示运行时错误3010(表已存在)。
如果要将数据插入现有表中,可以使用命令INSERT into USR_02_ALL select * FROM...
。除非您想消除重复项,否则将所有表组合成一个语句没有任何意义。相反,我将遍历表并为每个表分别发出INSERT
声明。有关更多详细信息,请参见例如https://docs.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/insert-into-statement-microsoft-access-sql
顺便说一句:正如Nathan在他的评论中写道:您不会发出SQL命令。您需要添加类似db.Execute sqlFinal
的语句。
答案 1 :(得分:0)
这是您目前的最终SQL:
SELECT * INTO USR_02_ALL FROM (
A_USR02_A UNION ALL SELECT * FROM A_USR02_A
B_USR02_B UNION ALL SELECT * FROM B_USR02_B
C_USR02_C UNION ALL SELECT * FROM C_USR02_C
如果要插入新表,它应该看起来像这样:
SELECT * INTO USR_02_ALL FROM
(
SELECT * FROM A_USR02_A
UNION ALL SELECT * FROM B_USR02_B
UNION ALL SELECT * FROM C_USR02_C
)
,或者如果要附加到现有表,则如下所示:
INSERT INTO USR_02_ALL
SELECT *
FROM (
SELECT * FROM A_USR02_A
UNION ALL SELECT * FROM B_USR02_B
UNION ALL SELECT * FROM C_USR02_C
)
此代码将构建该SQL(根据要使用的查询类型取消对 SQLFinal 行的注释):
Public Sub BuildQuery()
Dim SQLFinal As String
Dim SQL1 As String
Dim tdf As DAO.TableDef
Dim qdf As DAO.QueryDef
'Create a new table SQL
'SQLFinal = "SELECT * INTO USR_02_ALL FROM (SELECT * FROM "
'Append to existing table
SQLFinal = "INSERT INTO USR_02_ALL SELECT * FROM (SELECT * FROM "
SQL1 = " UNION ALL SELECT * FROM "
For Each tdf In CurrentDb.TableDefs
If tdf.Name Like "*USR02*" Then
SQLFinal = SQLFinal & tdf.Name & SQL1
End If
Next tdf
SQLFinal = Left(SQLFinal, Len(SQLFinal) - Len(SQL1)) & ")"
CurrentDb.CreateQueryDef("", SQLFinal).Execute
End Sub
请注意,它会在每个语句的末尾添加" UNION ALL SELECT * FROM "
,为下一个表名做好准备-然后它会删除该文本字符串的最后一个实例。