通过Excel VBA从SQL Server提取数据时发生运行时错误

时间:2019-06-05 14:17:38

标签: sql-server excel vba

我正在尝试使用VBA从SQL服务器获取一些数据以实现excel。在研究了网络之后,我整理了一段代码,并在执行该代码时抛出了

  

运行时错误-'2147217900(80040e14)':
  关键字“ ON”附近的语法不正确。

从该错误看来,由于查询中的某些异常而检测到该错误。该查询由DBA团队提供,并合并了来自2个不同表的数据。我使用相同的查询将数据从数据库手动导出到excel,并且可以正常工作。我不知道为什么vba会引发错误。任何帮助将不胜感激。谢谢。

Sub sync_data_vba_sqlserver()

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlQry As String, strCon As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
ActiveSheet.Cells.ClearContents

sqlQry = "SELECT A.PUMA_TSD_PollID AS ID, PUMA_TSD_FieldName AS Field_Name,PUMA_TSD_FieldValue AS Field_Value,PUMA_TSD_IPAddress AS IP_Address,PUMA_TSD_PollDate AS Poll_Date,PUMA_TSD_Channel AS Channel,PUMA_TSD_MachineName AS Machine_Name,PUMA_TSD_TestBedType AS TestBedType FROM [WWW_AUXMOD].[dbo].[tblPUMA_TSD_AVLLynx] A INNER JOIN [WWW_AUXMOD].[dbo].tblPUMA_TSD_AVLLynxData L ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID WHERE PUMA_TSD_MachineName != 'ELMS_SYSTEM' AND PUMA_TSD_PollDate >= '6/2/19';"


'---- Replace below highlighted names with the corresponding values

strCon = "Provider=sqloledb;Data Source=ECCDB1503.MD3Q.FORD.COM;Initial Catalog=WWW_AUXMOD;Integrated Security=SSPI"

'---  Open   the above connection string.

con.Open (strCon)

    rs.Open sqlQry, con
    ActiveSheet.Cells(2, 1).CopyFromRecordset rs
    rs.Close

con.Close
Set rs = Nothing


End Sub

期望从SQL Server导出到Excel的数据。

1 个答案:

答案 0 :(得分:0)

将查询拉出并粘贴到此处。在下面发表评论,但将其删除,改为“与”。您连续有2个ON。

SELECT A.PUMA_TSD_PollID AS ID, PUMA_TSD_FieldName AS Field_Name,PUMA_TSD_FieldValue AS Field_Value,PUMA_TSD_IPAddress AS IP_Address,PUMA_TSD_PollDate AS Poll_Date,PUMA_TSD_Channel AS Channel,
PUMA_TSD_MachineName AS Machine_Name,PUMA_TSD_TestBedType AS TestBedType 
FROM [WWW_AUXMOD].[dbo].[tblPUMA_TSD_AVLLynx] A 
INNER JOIN [WWW_AUXMOD].[dbo].tblPUMA_TSD_AVLLynxData L ON A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID 
    -- change ON to AND HERE  (ON IS REMOVED)
    --AND A.PUMA_TSD_PollID = L.PUMA_CH_TSD_PollID (Redundant statement) 
WHERE PUMA_TSD_MachineName != 'ELMS_SYSTEM' 
AND PUMA_TSD_PollDate >= '6/2/19'