为什么我在Excel中的SQL查询很慢?

时间:2015-01-09 13:32:16

标签: vba excel-vba excel-2013 excel

我使用函数查询数据库并在excel中返回结果。我调用该函数3次,返回所有数据大约需要15分钟。我在Aqua Data Studio中执行相同的查询,并在每个查询中获得20秒的结果。

我无法理解为什么在excel中这么慢。如何提高速度,是否可以更改代码以便更快地执行?

以下是我用VBA编写的函数。第一个是在第二个中调用的。

Function MyQuery(ConnString As String, ByVal QueryString As String, MyDestination As Range, DispName As String) As Boolean
'
' MyQuery(ConnString, QueryString, MyDestination, DispName)
'

   With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=ConnString, Destination:=MyDestination).QueryTable
        .CommandText = QueryString
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = False
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = DispName
        .Refresh BackgroundQuery:=False
    End With
    MyQuery = True
End Function

这是我编写SQL的第二个函数:

Sub GetData(DestinationRange As Range, QueryTableName As String, Lacs As String, Racs As String, StartTime As String, EndTime As String, Capacity As String)
'
'GetData(DestinationRange, QueryTableName, Lacs, Racs, StartTime, EndTime, Capacity)
'

Dim ConnectionString As String
Dim FuncFeedback As Boolean

ConnectionString = "ODBC;DSN=PostgreSQL30;DATABASE=xxxx;SERVER=xxx.xxx.xxx.xxx;PORT=5432;UID=xxxxx;;SSLmode=disable;ReadOnly=0;Protocol=7.4;FakeOidIndex=0;ShowOidColumn=0;RowVersioning=0;ShowSystemTables=0;ConnSettings=;Fetch=100;Socket=4096;UnknownSizes=0;MaxVarcharSize=255;MaxLongVarcharSize=8190;Debug=0;CommLog=0;Optimizer=0;Ksqo=1;UseDeclareFetch=0;TextAsLongVarchar=1;UnknownsAsLongVarchar=0;BoolsAsChar=1;Parse=0;CancelAsFreeStmt=0;ExtraSysTablePrefixes=dd_;;LFConversion=1;UpdatableCursors=1;DisallowPremature=0;TrueIsMinus1=0;BI=0;ByteaAsLongVarBinary=0;UseServerSidePrepare=1;LowerCaseIdentifier=0;GssAuthUseGSS=0;XaOpt=1"


Query1 = " SELECT "
Query1 = Query1 & "TIMESTAMP::DATE::TEXT, "

'...
' AND HERE I WRITE THE SQL QUERY THIS WAY, THE WHOLE QUERY IS NOT INCLUDED
'...

Query1 = Query1 & " WHERE "
Query1 = Query1 & " (TIMESTAMP BETWEEN '" & StartTime & "' AND '" & EndTime & "')"  


FuncFeedback = MyQuery(ConnectionString, Query1, DestinationRange, QueryTableName)
            ' MyQuery(ConnString, QueryString, MyDestination, DispName)

End Sub

1 个答案:

答案 0 :(得分:0)

尝试添加MS Power Query加载项。从不同来源获取数据非常有效。您还可以在将收集的数据加载到Excel als表之前对其进行转换。 Power Query具有一些使用限制,具体取决于您使用的Excel 2013(例如Professional)的版本。