将记录从非索引字段导入到索引字段中:访问VBA和SQL

时间:2018-07-13 23:07:36

标签: sql ms-access access-vba

我有一个新组织的Access 2016后端,正在尝试从当前Access 2000数据库导入记录。以下记录可以很好地导入:

Sub tblOrders_FillTable()

Dim SQL As String

SQL = "INSERT INTO tblOrders (OrderNumber, AccountNumber, DateIn, Shipping, PONumber) " & _
      "SELECT ORDERNumber, Account, DateIn, Shipping, PONumber FROM tblOrder IN " & _
      "'" & strPath & "';"
DoCmd.RunSQL SQL

End Sub

OrderNumber是新表和旧表的主键,因此将其编入索引。在我需要填充的另一个表中,旧表没有主键,也没有索引,但是新表的确有一个字段是主键,因此已被索引。

我正在做的是将所有旧记录都放入一个重复键表(以单独保存),然后仅将非重复记录和非空记录带入带有主键字段的新表中。 (然后,我将从重复键表中删除非重复记录)

Sub tblCustomerEQ_FillTable()

Dim SQL As String

'Fill the duplicates table since this table has no primary key
SQL = "INSERT INTO `*tblDuplicateCustomerEQKeys` (CustomerEQIDNumber, AccountNumber, SecondEQIDNumber, " & _
      "UnitDescription, MFG, Model, LastDateIn, IntervalInDays, ExpirationDate, Price, " & _
      "Department) SELECT `CustomerEQID #`, `ACCOUNT #`, `Second EQID#`, `UNIT Description`, " & _
      "MFG, MODEL, `LAST DATE IN`, `INTERVAL IN DAYS`, `EXPIRATION DATE`, PRICE, " & _
      "`DEPT NO` FROM tblCustomerEQ IN '" & strPath & "';"
DoCmd.RunSQL SQL

'Find duplicate keys & insert them into the Count table
SQL = "INSERT INTO `*tblCountCustomerEQDuplicateKeys` " & _
      "SELECT COUNT(*) AS NumberOfDuplicates, " & _
      "`*tblDuplicateCustomerEQKeys`.CustomerEQIDNumber AS DuplicateCustomerEQIDNumbers " & _
      "FROM `*tblDuplicateCustomerEQKeys` GROUP BY " & _
      "`*tblDuplicateCustomerEQKeys`.CustomerEQIDNumber " & _
      "HAVING COUNT(*) > 1;"
DoCmd.RunSQL SQL

'Insert records that are not duplicates and are not null into indexed table
SQL = "INSERT INTO tblCustomerEQ " & _
      "SELECT * FROM `*tblDuplicateCustomerEQKeys` " & _
      "WHERE `*tblDuplicateCustomerEQKeys`.CustomerEQIDNumber IS NOT NULL AND " & _
      "`*tblDuplicateCustomerEQKeys`.CustomerEQIDNumber NOT IN " & _
      "(SELECT DuplicateCustomerEQIDNumbers " & _
      "FROM `*tblCountCustomerEQDuplicateKeys`);"
DoCmd.RunSQL SQL

由于我要插入到新表中的记录不是重复的,也不是null,因此我认为可以满足主键字段的要求,并且insert into语句可以正常工作。但是,当我运行SQL语句时,查询永远不会结束。

我当时想我可以删除主键索引对象,然后重新创建主键索引对象,但这会破坏我的表关系。

我认为有人必须具有一种方法,可以从表中导入记录而不用索引建立表索引(如果这实际上是我的SQL语句永不结束的原因)。

感谢您的时间!

0 个答案:

没有答案