VBA/Excel:不接受 SQL 子条款

VBA/Excel: Not accepting SQL subclauses

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

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

我的 SQL 在没有 Excel 的情况下直接 运行 时工作正常。但是 Excel/VBA 的 With As 子句有问题并抛出 "Run-Time error '3704'; Application-defined or object-defined" 错误。这是我的 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 语句,则一切正常。谢谢指教。

您必须在 VBA 中编写嵌套的 select 语句。尝试

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

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

select start_value, country
into #TempTable
from MYTABLE where country = '840'

Select * from #TempTable

DROP TABLE #TempTable