使用MS Access,通过VBA,我一直试图从结构相同的外部Access数据库表中更新主Access数据库表。相同的列,相同的字段。外部数据库用于更新中央主数据库。
我一直试图开发的是一行SQL,它仅附加完全唯一的条目。因为没有外键或唯一的标识符可以引用传入的数据,所以我需要检查每个字段以确保没有确切的重复项。因此,如果表具有2个字段,则如果条目未通过逻辑测试
intTable.field1 = extTable.field1 And intTable.field2 = extTable.field2
那么这些就是要附加的条目。
下面提供了我想出的代码,当它运行时,它尝试将所有内容附加(以Gary Oldman的声音表示)。我无法找出问题所在,因为它几乎忽略了WHERE
或WHERE NOT EXIST
。我尝试了数十种小的修改和替代版本。要么全部要么不追加。
INSERT INTO Table1
SELECT field1, field2, field3, field4, field5
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB
WHERE NOT EXISTS (SELECT *
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB1
WHERE ('Table1.[field1]'='sourceDB1.[field1]' And
'Table1.[field2]'='sourceDB1.[field2]' And
'Table1.[field3]'='sourceDB1.[field3]' And
'Table1.[field4]'='sourceDB1.[field4]' And
'Table1.[field5]'='sourceDB1.[field5]'));
最终代码(在实施ArcherBird解决方案之后):
INSERT INTO Table1
SELECT field1, field2, field3, field4, field5
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB
WHERE NOT EXISTS (SELECT *
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB1
WHERE ((sourceDB.[field1] = sourceDB1.[field1] Or (sourceDB.[field1] IS NULL And sourceDB1.[field1] IS NULL)) And
(sourceDB.[field2] = sourceDB1.[field2] Or (sourceDB.[field2] IS NULL And sourceDB1.[field2] IS NULL)) And
(sourceDB.[field3] = sourceDB1.[field3] Or (sourceDB.[field3] IS NULL And sourceDB1.[field3] IS NULL)) And
(sourceDB.[field4] = sourceDB1.[field4] Or (sourceDB.[field4] IS NULL And sourceDB1.[field4] IS NULL)) And
(sourceDB.[field5] = sourceDB1.[field5] Or (sourceDB.[field5] IS NULL And sourceDB1.[field5] IS NULL)) ));
答案 0 :(得分:1)
1)从字段比较逻辑中删除字符串引号。
2)您在查询中将Table1
别名为sourceDB
,因此请使用该引用。
3)检查不存在的表应该是Table1
的“本地”版本(您要插入的表)。
INSERT INTO Table1
SELECT field1,
field2,
field3,
field4,
field5
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB
WHERE NOT EXISTS (SELECT *
FROM [Table1] sourceDB1
WHERE (sourceDB.[field1] = sourceDB1.[field1] And
sourceDB.[field2] = sourceDB1.[field2] And
sourceDB.[field3] = sourceDB1.[field3] And
sourceDB.[field4] = sourceDB1.[field4] And
sourceDB.[field5] = sourceDB1.[field5]));
编辑:
要处理这些字段可能具有null
值的情况,由于=
不等于null
,因此无法进行简单的null
比较。我可以想到的最好的解决方法是在MS Access中用不太可能使用的其他值替换null
。这样做时,还需要确保选择的替换值与数据类型一致。我将假设您所有的字段均为文本。
INSERT INTO Table1
SELECT field1,
field2,
field3,
field4,
field5
FROM [;DATABASE=C:\extDB.accdb].[Table1] sourceDB
WHERE NOT EXISTS (SELECT *
FROM [Table1] sourceDB1
WHERE (nz(sourceDB.[field1],"!@#") = nz(sourceDB1.[field1],"!@#") And
nz(sourceDB.[field2],"!@#") = nz(sourceDB1.[field2],"!@#") And
nz(sourceDB.[field3],"!@#") = nz(sourceDB1.[field3],"!@#") And
nz(sourceDB.[field4],"!@#") = nz(sourceDB1.[field4],"!@#") And
nz(sourceDB.[field5],"!@#") = nz(sourceDB1.[field5],"!@#")));