VBA ADO中的以下SQL提供'From子句中的語法錯誤'錯誤。Excel VBA ADO SQL - From子句中的語法錯誤
Sub RunSQL2()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim ws As Worksheet
Dim strRangeAddress As String
Dim dataRange As Range
strFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
Set ws = ThisWorkbook.Sheets("mydata")
strRangeAddress = ActiveSheet.Name & "$" & ws.Range("A1:C30020").Address(False, False)
strSQL = strSQL & " (select s.* from "
strSQL = strSQL & " (select t.*, row_number() over (partition by child_level order by child_index,child_level) [rownum] from [" & strRangeAddress & "] t) s "
strSQL = strSQL & " where [rownum] = 1) u "
strSQL = strSQL & " join (select t2.*, 1 as [rownum] from [" & strRangeAddress & "] t2) v "
strSQL = strSQL & " on (v.parent_level = u.child_level and v.[rownum] = u.[rownum]) "
strSQL = strSQL & " union select w.child_index,w.child_level,w.child_level,w.child_index "
strSQL = strSQL & " from [" & strRangeAddress & "] w "
strSQL = strSQL & " where w.child_index = 1 "
strSQL = strSQL & " order by v.child_index;"
rs.Open strSQL, cn
Debug.Print rs.GetString
End Sub
STRSQL的debug.print是:
select v.child_index,v.child_level,v.parent_level,u.child_index as parent_index
from
(select s.*
from
(select t.*, row_number() over (partition by child_level order by child_index,child_level) [rownum]
from [mydata$A1:C30020] t
) s
where [rownum] = 1
) u
join
(select t2.*, 1 as [rownum]
from [mydata$A1:C30020] t2
) v on (v.parent_level = u.child_level and v.[rownum] = u.[rownum])
union
select w.child_index,w.child_level,w.child_level,w.child_index
from [mydata$A1:C30020] w
where w.child_index = 1
order by v.child_index;
當我用簡單的字符串STRSQL連接工程並返回結果。這工作:
strSQL = "SELECT * FROM [" & strRangeAddress & "]"
我想我有正確的語法。是否有可能從不兼容的SQL中產生錯誤?例如,ADO可以做'分區'?
我正在使用Excel 2010 64位Office。
我已經重新格式化你的長聯SQL查詢,因爲它不是完全可以理解。審覈通過後,再次檢查查詢以確保這是正確的。稍後我會更好地看待您的問題 –
** Pro提示**:當您使用'strSQL = strSQL&'在您的代碼中構建如此冗長而複雜的查詢時,請在每行末尾添加一個'&vbcrlf'所以查詢變得可以理解,當你'debug.print strSQL' –
你用來連接到Excel工作簿的Jet/ACE SQL引擎不支持其方言中的窗口函數,所以你不能使用'RowNumber()','Over ()'或'分區'。 – Parfait