简体   繁体   中英

Get Query Result from SQL Server with VBA without CopyFromRecordSet

I have the following VBA query from SQL-Server, returning just one result. My question is how to read it. So far I have found one way to do it, but I do not want to use it.

Dim rsData              As Object
Set rsData = CreateObject("ADODB.Recordset")

With rsData
    .ActiveConnection = cnLogs
    .Open "USE DB SELECT [VersionNumber] FROM Main WHERE [IsLastCurrent] = 1"
End With

Solution I do not want to use:

Cells(1, 1).CopyFromRecordset rsData

Try this change in SQL command:

With rsData
    .ActiveConnection = cnLogs
    .Open "USE DB; SELECT [VersionNumber] FROM Main WHERE [IsLastCurrent] = 1;"
End With

If (rsData.EOF = False) OR (rsData.BOF = False) Then
 'there are recordset
 myVar=   rsData.Fields(0).value
End If

rsData.Close

You can access the values in a Recordset record by record using the Fields property. When you first open a recordset, it is either empty (in which case recordset.BOF and recordset.EOF are both true) or it points to the first record in the set (in which case recordset.BOF and recordset.EOF are both false). You then access the data in that record using (for example):

rsData.Fields("VersionNumber").Value

and you can move through the records (if you have more than one) using the MoveFirst , MoveLast , MoveNext , and MovePrevious methods of the recordset object.

If you want to keep the data in memory, use an array variable like Dim rsArray as variant and then copy the record set to it with:

rsArray = rsData.GetRows

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