VBA / Excel:不接受SQL子条款

我有一个Excel / VBA电子表格通过ADODB连接到Oracle数据库。 连接工作正常,普通查询运行良好。 但我试图有点聪明,避免使用with as子句运行多个select语句。 这个链接基本上解释了我想要做的事情:

https://dba.stackexchange.com/questions/6368/how-to-select-the-first-row-of-each-group

我的SQL在没有Excel的情况下直接运行时工作正常。 但是,Excel / VBA With As子句出现问题,并引发“运行时错误”3704“应用程序定义的或对象定义的”错误。 这是我的SQL和代码的简化版本:

SQL

 with ORDERED as (select start_value, country from MYTABLE where country = '840') select * from ORDERED 

VBA代码

 Dim dbaRecordSet As ADODB.Recordset Dim gloDatabase As ADODB.Connection dim sSQL as string sSQL = "with ORDERED as (select start_value, country from MYTABLE where country = '840') select * from ORDERED" Set gloDatabase = New ADODB.Connection gloDatabase.ConnectionString = My_Connection_String gloDatabase.Open gloDatabase.CursorLocation = adUseClient Set dbaRecordSet = New ADODB.Recordset dbaRecordSet.ActiveConnection = DBConnection dbaRecordSet.CursorLocation = adUseClient dbaRecordSet.Source = sSQL dbaRecordSet.Open 

有谁知道为什么Excel / VBA拒绝接受With As ()子句? 如果我删除该条款并作为普通的select语句运行,一切工作正常。 感谢您的build议。

你必须在VBA中写一个有点不同的嵌套select语句。 尝试

 select * from ( select start_value, country from MYTABLE where country = '840' ) ORDERED 

您是否尝试过使用临时表而不是With As子句?

 select start_value, country into #TempTable from MYTABLE where country = '840' Select * from #TempTable DROP TABLE #TempTable