我需要在Access 2016中使用SQL VBA插入多个行和字段。我正在做下面这件事 - 有了工会 - 但它不起作用,它说我的工会的sintax是错的。我需要弄清楚出了什么问题,否则一个接一个地运行查询,我有9个像这样! (编辑:找到解决方案!)
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier) SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & " union "
query = query & "SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & ""
这是有效的答案,非常类似于有人在下面给我看的代码,但差异改变了一切(没有错误消息,它确实插入表中!)。我必须将选择放入选择中,仍然给我一个错误,并且出于某种原因,当我添加 - >作为价格和数量它的工作。我现在还不确定它为什么会有效,如果你有解释,请告诉我!
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier ) SELECT * FROM (SELECT qryTotals.JRN as Quantity, qryTotals.[Rate JRN] as Price, qryTotals.MMDCarrier FROM qryTotals where qryTotals.MMDCarrier like '" & Me.Combo0 & "'"
query = query & " UNION SELECT qryTotals.MG , qryTotals.[Rate MG], qryTotals.MMDCarrier From qryTotals where qryTotals.MMDCarrier like '" & Me.Combo0 & "')"
答案 0 :(得分:2)
如果您将INSERT INTO ... SELECT
与联合使用,则需要将所有联合放入子查询中,例如:
INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier)
SELECT * FROM (
SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN], qryTotals.MMDCarrier from qryTotals
where qryTotals.MMDCarrier like 'something'
UNION
SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],
qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like 'somethingElse'
) As A
或者,在您的VBA实施中:
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier) SELECT * FROM (SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & " union "
query = query & "SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & ") As A"
请注意,您的查询还在INSERT INTO
部分中包含一个尾随逗号,这不是Access SQL中的语法错误,但在大多数其他形式的SQL中都是一个,但仍然是一种不好的做法。此外,LONG可能是对的,你想要那些单引号(但实际上,你应该使用参数)