简体   繁体   English

使用 VBA 不使用 CopyFromRecordSet 从 SQL 服务器获取查询结果

[英]Get Query Result from SQL Server with VBA without CopyFromRecordSet

I have the following VBA query from SQL-Server, returning just one result.我有以下来自 SQL-Server 的 VBA 查询,仅返回一个结果。 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: 在SQL命令中尝试以下更改:

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. 您可以通过使用Fields属性的记录来访问Recordset记录中的值。 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). 首次打开记录集时,它要么为空(在这种情况下recordset.BOFrecordset.EOF均为true),要么指向该集中的第一个记录(在这种情况下recordset.BOFrecordset.EOF均为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. 您可以通过记录使用移动(如果你有一个以上的) MoveFirstMoveLastMoveNext ,和MovePrevious的方法recordset对象。

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:如果要将数据保留在 memory 中,请使用像 Dim rsArray这样的数组变量作为变体,然后将记录集复制到它:

rsArray = rsData.GetRows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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