使用Excel vba执行.sql文件,其中(.sql)查询包含来自Linked Server的联接

时间:2017-07-04 20:01:34

标签: sql-server

我需要使用Excel VBA宏从C:Drive运行.SQL查询。以下代码不适用于链接服务器

从下面的代码Final.sql:LATESTDUMP和OLDDUMP是linkedServer

Final.sql 代码

 INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 
8.0;Database=C:\Queries\Results\DumpQuery.xlsx;','SELECT * FROM  [Table1$]') 
SELECT * FROM (
    SELECT  *
    FROM LATESTDUMP...Table1) t1

FULL OUTER JOIN (
    SELECT *
    FROM OLDDUMP...Table1) t2

ON t1.id = t2.id

WHERE
    t1.id IS NULL OR
    t2.id IS NULL    

执行Final.sql的VBA代码

Sub Sqlquery()
Dim Cnn As New ADODB.Connection
Dim Rst As New ADODB.recordSet
Dim ConnectionString, SqlTextFile, SqlStatement As String

    'Application.ScreenUpdating = False

 'Connection to SQl Server
ConnectionString = "Provider=SQLOLEDB.1;" & _
"Integrated Security=SSPI;" & _
"Data Source=MOLP0533183"

Cnn.Open ConnectionString
Cnn.CommandTimeout = 900

Dim strSQL As String
strSQL = ""

Dim hnd As Integer
hnd = FreeFile

Application.ScreenUpdating = False


Open "C:\Queries\Final.sql" For Input As hnd

Dim row As String
Do Until EOF(hnd)
    Line Input #hnd, row
    strSQL = strSQL & row & vbNewLine


Loop

Close #hnd

Debug.Print strSQL

Rst.Open strSQL, Cnn

End Sub

VBA代码正在执行而没有错误,但我没有在DumpQuery.xlsx中获得任何输出

0 个答案:

没有答案