通过QueryTables使用变量运行查询

时间:2019-11-29 09:24:05

标签: sql excel vba variables odbc

我创建了一个基本的Sub来运行查询,并在单元格A1中的活动工作表中返回结果。

Sub MySub()
'Assemble the connection string
 strDSN = "MyDSN"
 strPass = "MyPass"
 strUsername = "MyUser"
 strConnection = "ODBC;DSN=" & strDSN & ";UID=" & strUsername & ";PWD=" & strPass
 strQuery = "MyQuery"

 With ActiveSheet.QueryTables.Add(Connection:=strConnection, Destination:=Cells(1, 1))
        .CommandText = strQuery
        .FieldNames = True
        .RefreshStyle = 0
        .AdjustColumnWidth = True
        .Refresh BackgroundQuery:=False
 End With
End Sub

此子项可与以下查询配合使用: Select distinct TOP 3 Time FROM [WBServiceLogs]

如果我在SQL中声明一个变量,例如,sub将失败: Declare @Shift INT SET @Shift = 100 Select distinct TOP 3 Time + @Shift FROM [WBServiceLogs]

我收到一个错误:Application-defined or object-defined error

查询本身是可以的,它在SQL Server Mgt Studio中运行良好。或例如通过ODBC WinSQL。

有什么建议吗?谢谢!

0 个答案:

没有答案
相关问题