从外部文件或变量读取SQL Server查询ADODB.Connection

时间:2018-06-22 17:39:40

标签: sql excel vba connection-string

我有此Excel VBA代码:

Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String
    Dim query As String

    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=xxxx.xxx.xxxx.xxx,xxxx;" & _
                  "Initial Catalog=mydb;" & _
                  "Trusted_Connection=yes;"

    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute("")

    ActiveSheet.Range("A2").CopyFromRecordset rs
    ...
End Sub

一切正常。

问题在此部分中:Set rs = conn.Execute("")

我的select语句查询太大,将其分成连续行是不现实的。

是否可以从文件或变量中读取查询文本?

非常感谢您

2 个答案:

答案 0 :(得分:0)

Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String
    Dim query As String

    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=xxxx.xxx.xxxx.xxx,xxxx;" & _
                  "Initial Catalog=mydb;" & _
                  "Trusted_Connection=yes;"

    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute.
    conn.Open sConnString

    'read SQL from file
    query = GetContent("C:\Stuff\myQuery.txt")

    Set rs = conn.Execute(query)

    ActiveSheet.Range("A2").CopyFromRecordset rs
    ...
End Sub


'read all file content
Function GetContent(f As String) As String
    GetContent = CreateObject("scripting.filesystemobject"). _
                  opentextfile(f, 1).readall()
End Function

或者,将您的SQL存储在工作表单元格中,然后从那里读取它。

答案 1 :(得分:0)

您不必使用续行,您可以附加字符串并附加vbCrLf字符。例如

Dim sSQL as string
sSQL = "SELECT" & vbCrLf
sSQL = sSQL & "AField" & vbCrLf
sSQL = sSQL & ",BField" & vbCrLf
sSQL = sSQL & ",(SELECT XField FROM AnotherTable ..........) as XField" & vbCrlf
'and so on and so on
Set rs = conn.Execute(sSQL)

您可以通过这种方式构建非常长的SQL语句。