RawlinsCross
Active Member
- Joined
- Sep 9, 2016
- Messages
- 437
I have a function where you pass through a SQL database table name and an optional string query (if non supplied the query becomes the 'Select *' from the table). I want to pass the returning record set to a variant array. When attempting the code, it all works fine but it's awfully slow. So I stepped through the code and found that the "rs.Open ....." line is quite fast, but the "rs.GetRows()" line is very very slow. Is there a faster alternative?
VBA Code:
Public Function GetSQLTable(sTable As String, Optional sSuppliedQuery As String) As Variant
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
Dim i As Long
Dim ListObj As ListObject
Dim vTable As Variant
Dim sQuery As String
Set rs = New ADODB.Recordset
If sSuppliedQuery = "" Then
sQuery = "Select * From " & sTable
Else
sQuery = sSuppliedQuery
End If
Server_Name = "ServerName"
Database_Name = "DBName"
User_ID = "USERID"
Password = "PASSWORD123" ' not the real password ;)
SQLStr = sQuery
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic '<- this step is fast
vTable = rs.GetRows() '<- growing old at this step
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
GetSQLTable = vTable
End Function