第二个QueryDefs.SQL不起作用

时间:2017-01-02 15:29:24

标签: vba ms-access access-vba

我在Access VBA中有代码,用SQL填充查询模板并执行它。我要查询。第一个工作正常,但是当我分配SQL字符串时,我得到错误3305。

两个插入的表都在Oracle DB上,并且我已将表链接到它。

Sub prc()
Dim pSQLStr      As String        
Dim pQuery       As QueryDef   
Dim pBaza        As Database  

Set pBaza = CurrentDb
Set pQuery = pBaza.QueryDefs("qryInsertTemplate")

pSQLStr = ""
pSQLStr = pSQLStr & "INSERT INTO tbl1 ("
pSQLStr = pSQLStr & "ID, POS)"
pSQLStr = pSQLStr & "SELECT xlsx.ID, xlsx.pos"    
pSQLStr = pSQLStr & " FROM xlsx;"

With pQuery
    .SQL = pSQLStr
    .ReturnsRecords = False
    .Execute
End With

Set pQuery = pBaza.QueryDefs("qryInsertTemplate")

pSQLStr = ""
pSQLStr = pSQLStr & "INSERT INTO tbl2 ("
pSQLStr = pSQLStr & "ID, POS)"
pSQLStr = pSQLStr & "SELECT xlsx.ID, xlsx.pos"    
pSQLStr = pSQLStr & " FROM xlsx;"

With pQuery
    .SQL = pSQLStr 'here I got error 3305
    .ReturnsRecords = False
    .Execute
End With

End Sub

1 个答案:

答案 0 :(得分:1)

尝试 - 在第二次运行之前 - 关闭对象:

pQuery.Close
Set pQuery = Nothing
Set pQuery = pBaza.QueryDefs("qryInsertTemplate")

或创建qryInsertTemplate的副本并第二次运行:

Set pQuery = pBaza.QueryDefs("qryInsertTemplateCopy")