Access中的重复输出目标错误

时间:2017-06-05 15:36:58

标签: sql ms-access

我正在使用以下查询。但是当我运行它时,它会给出错误

  

"重复输出目的地' ShipmentID'。

CurrentDb.Execute "INSERT INTO TmpContainersForPLReport " & _
                  "SELECT * FROM Containers INNER JOIN Shipments ON (Containers.ShipmentID = Shipments.ShipmentID)  WHERE Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.PONumber = '" & TxtPONumber & "'" & _
                  " OR Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.SalesOrderNumber = '" & txtSalesOrderNumber & "'"

2 个答案:

答案 0 :(得分:1)

您正在使用' SELECT *'来自两个表之间的JOIN,并且两个表中都存在ShipmentID字段,因此您选择该字段两次。

如果您转到此链接,您会看到此错误的说明:

https://msdn.microsoft.com/en-us/library/bb209781(v=office.12).aspx

答案 1 :(得分:1)

从联接中,可以看到 ShipmentID 驻留在两个表中, Containers Shipments ,因而错误。出于这个原因,请始终明确引用列,而不是缩写为*。即使如此明确地引用INSERT子句中的目标列。

作为另一种最佳实践,请考虑字符串连接的参数化。您可以DAO querydef parameters使用PARAMETERS子句。见下面的例子。请更换 Cols

Dim strSQL As String
Dim qdef As QueryDef

strSQL = "PARAMETERS TxtEntryDateParam Date, TxtPONumberParam Text(255), TxtSalesOrderNumberParam Text(255);" & _
         "INSERT INTO TmpContainersForPLReport (Col1, Col2, Col3) " & _
         "SELECT Col1, Col2, Col3 FROM Containers c " & _
         "INNER JOIN Shipments s ON (c.ShipmentID = s.ShipmentID) " & _
         "WHERE c.PackinglistentryDate = [TxtEntryDateParam] AND c.PONumber = [TxtPONumberParam]" & _
         "   OR c.PackinglistentryDate = [TxtEntryDateParam] AND c.SalesOrderNumber = [TxtSalesOrderNumberParam];"

Set qdef = CurrentDb.CreateQueryDef("", strSQL)

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!TxtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing

实际上,您甚至可以将上面的SQL保存为已保存的Access查询,Jet / ACE引擎会缓存该查询以获得最佳优化的执行路径(即,比VBA字符串查询更有效):

Dim strSQL As String

Set qdef = CurrentDb.QueryDefs("myAppendQuery")

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!txtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing