我试图通过VBA传递查询字符串以从redshift服务器提取数据。
查询在数据库环境中运行良好,我确信我的数据库连接在VBA代码中设置正确。
我收到此错误: 语法错误在或附近" GO&#34 ;;
我猜测它的间距问题是" GO"在查询和下一个Select语句中,但我无法弄清楚如何解决这个问题。同样,查询在Aqua Data Studio中运行得很好。
VBA:
Sub LoadQuery1(intRow, intCol, strWSheet, strConnection, intConnection)
Dim cmd As ADODB.Command
Dim rsPubs As ADODB.Recordset
Dim i As Integer
Dim Rowcount As Long
Dim irows As Integer
Set cmd = New ADODB.Command
If intConnection = 14 Then
If OpenConnection1() Then
'Set up the command object and execute
Set rsPubs = New ADODB.Recordset
With cmd
.ActiveConnection = conn1
.CommandText = strConnection
.CommandType = adCmdText
.CommandTimeout = 0
End With
rsPubs.Open cmd, , , , adCmdText
'rsPubs.Open cmd, , adOpenStatic, adLockReadOnly
End If
End If
irows = intRow + 1
Do While Not rsPubs.EOF
'update header
For i = 0 To rsPubs.Fields.Count - 1
Worksheets(strWSheet).Cells(intRow, intCol + i) = rsPubs.Fields(i).Name
Next i
For i = 0 To rsPubs.Fields.Count - 1
Worksheets(strWSheet).Cells(irows, intCol + i) = rsPubs.Fields(i).Value
Next i
rsPubs.MoveNext
irows = irows + 1
Loop
End Sub
SQL :(示例)
Select Distinct
sessionid
,dorderid
,userid
,customerid
,bookings
,dtmcreated
into #FinalMetrics
From #RawMetrics
GO /*This is the GO throwing the error.*/
select
searchengine
,count(distinct sessionid) as Sessions
,count(distinct userid) as Visitors
,count(distinct orderid) as Orders
,cast(sum(bookings) as float)/100 as bookings
,cast(count(orderid) as float)/count(sessionid) as CR
from #FinalMetrics
Group by
searchengine;
其他说明: 我尝试用分号替换GO,但是然后查询在最终的select语句之前停止,并且实际上并没有拉出记录集。
由于
答案 0 :(得分:0)
使用vbCrLf
分隔您的SQL语句。
例如:
Dim strSql
strSql = "select col1 from table1" & vbCrLf
strSql = strSql & "select col1 from table2"
With cmd
....
.CommandText = strSql
End With
然后使用Recordset.NextRecordset
加载您的第二个select
声明的结果:
rsPubs.Open cmd, , , , adCmdText
....
rsPubs.NextRecordset