I have a few SQL server tables, one with 200,000 rows and the other 900,000 rows, both with maybe 50 columns. I need to download them to a csv file, and within VBA script (it's inside Excel). All rows and all columns are required to be exported.
Presume you have a recordset oRec taken from a simple query. All columns are varchars, most are either varchar(20) or varchar(200)
'SELECT * FROM TABLE'.
In the below code I loop through the recordset and then through each column. If I comment out column looping or just get the first column it's pretty fast. But every column is exponentially making it worse to taking over an hour.
Is there a better way? I need every row and column and VBA/Excel is the only way as it's part of a system within Excel to process data. This is for end users and so they don't have sql tools, libraries (just office) and I cannot distribute applications. This export is just one tiny part of a larger Excel automation project.
While Not oRec.EOF
sLine = ""
LineCount = LineCount + 1
For Each col In oRec.Fields
If IsNull(col.value) Then
sVal = "NULL"
Else
sVal = col.value
End If
If Not bHaveHeader Then
sHeader = sHeader & CStr(col.name) & ","
sLine = sLine & "," & sVal
Else
sLine = sLine & "," & sVal
End If
colOffset = colOffset + 1
Next
colOffset = 0
If bHaveHeader Then
sLines = sLines & Right(sLine, Len(sLine) - 1) & vbCrLf
Else
If LineCount Mod EXPORT_LINE_BUFFER = 0 Then
'lines ready to be exported. last line can't have carriage return
sLines = sHeader & vbCrLf & sLines & Right(sLine, Len(sLine) - 1)
Call UpdateFile(fs, sExportFile, sLines)
sLines = ""
Else
sLines = sHeader & vbCrLf & sLines & Right(sLine, Len(sLine) - 1) & vbCrLf
End If
End If
bHaveHeader = True
oRec.MoveNext
Wend