简体   繁体   中英

SQL CopyFromRecordSet got slow - Auto Wrapping and Sizing

Using Excel VBA to pull data from MS SQL into Excel. It is only 2,000 rows and 30 columns but it is taking over 10 minutes to execute the line .CopyFromRecordset .

I believe the culprit to be the fact that when it is pasting into Excel from SQL some auto formatting is occurring. I notice that wrap text occurs automatically as well as some row and column sizing. Not sure how to turn this off.

Any help would be greatly appreciated!

Sub ADOExcelSQLServer()

   ' Objects 2.x library     

    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset

    Server_Name = "eq-t-sql01" 
    Database_Name = "HSCSN_DR" 
    SQLStr = "SELECT e.*, m.DOB FROM [HSCSN_DR].[dbo].[EPSDT_Call_Log_Answers] e join HSCSN_DR..Q_MEMBERS m on m.MedicaidID = e.MedicaidID Order By [Attempt 1 Date] Desc, MedicaidID"

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";Trusted_connection=yes;"
    '& _";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic
     ' Dump to spreadsheet
    With Worksheets("Data").Range("A2") ' Enter your sheet name and range here
        .ClearContents
        .CopyFromRecordset rs
    End With

    rs.Close
    Set rs = Nothing
    Cn.Close
End Sub

Solved this!

For some reason, changing the SELECT statement in the VBA code to a SQL Stored Proc then executing it that way removed auto-formatting issues that were occurring and increased the execution time from 8 minutes to 2 seconds.

Didn't change the SQL statement in anyway in MS SQL or the stored proc. Can anyone provide insight on why this fixed the issue?

    Server_Name = "eq-t-sql01"
    Database_Name = "HSCSN_REFERENCE_TABLES"
    SQLStr = "[EPSDT_Call_Log_with_Member_Info]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM