2015-05-21 47 views
2

我有一个Excel/VBA电子表格通过ADODB连接到Oracle数据库。连接工作正常,普通查询运行良好。但我试图有点聪明,并避免使用with as子句运行多个select语句。这个环节主要讲解什么,我试图做的:当它直接运行而不Excel中VBA/Excel:不接受SQL子条款

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

我的SQL工作正常。但是,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语句运行,则一切正常。谢谢你的建议。

+0

您可以添加您收到的运行时错误吗?它可以帮助人们回答这个问题,并帮助未来的访问者找到问题。 – RubberDuck

+0

其运行时错误'3704';应用程序定义或对象定义的错误 – user3046742

+0

太棒了,请将其编辑到您的问题中 – RubberDuck

回答

2

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

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

工作正常!谢谢。 – user3046742

1

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

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

Select * from #TempTable 

DROP TABLE #TempTable