我有一个SQL查询,我想将其存储在vba变量中,然后获取输出的行数。
我有以下内容:
Dim PortInfo As Variant
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim lStr As String
Dim LastRow As Long
strServer = "DB-01"
ConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";" & _
"Integrated Security=SSPI;"
cnn.Open ConnectionString
lStr = "SELECT [PORTINFOID],[PORTNAME] FROM [a].[dbo].[portinfo]"
rst.Open lStr, cnn
If Not rst.EOF And Not rst.BOF Then
For i = 0 To rst.Fields.Count - 1
PortInfo = PortInfo & rst.Fields(i).name & vbTab
Next
Do Until rst.EOF
For i = 0 To rst.Fields.Count - 1
PortInfo = PortInfo & rst.Fields(i) & vbTab
Next
rst.MoveNext
Loop
End If
rst.Close
MsgBox PortInfo
LastRow = ???
通过以上操作,我得到以下信息:
首先,我不确定PortInfo
变量是否应为Variant
。而且如果应该的话,如何使输出以列/行的方式显示,以便获得结果表的行数。
答案 0 :(得分:2)
一些建议:
PortInfo
变量的类型可以为String
。strServer
变量已过时。vbTab
作为列分隔符时,请使用vbCrLf
作为行分隔符。LastRow
变量。New
,因为这些变量无法清除。Option Explicit
来强制自己声明所有变量(例如i
)。例如,代码可能如下所示:
Dim PortInfo As String
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim lStr As String
Dim LastRow As Long
Dim i As Integer
ConnectionString = "Provider=SQLOLEDB;Data Source=DB-01;" & _
"Initial Catalog=a;Integrated Security=SSPI;"
lStr = "SELECT [PORTINFOID],[PORTNAME] FROM [dbo].[portinfo]"
Set cnn = New ADODB.Connection
cnn.Open ConnectionString
Set rst = New ADODB.Recordset
rst.Open lStr, cnn
With rst
If Not .EOF And Not .BOF Then
For i = 0 To .Fields.Count - 1
PortInfo = PortInfo & .Fields(i).Name
If i < .Fields.Count - 1 Then
PortInfo = PortInfo & vbTab
Else
PortInfo = PortInfo & vbCrLf
End If
Next
End If
Do Until .EOF
LastRow = LastRow + 1
For i = 0 To .Fields.Count - 1
PortInfo = PortInfo & .Fields(i)
If i < .Fields.Count - 1 Then
PortInfo = PortInfo & vbTab
Else
PortInfo = PortInfo & vbCrLf
End If
Next
rst.MoveNext
Loop
End With
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
MsgBox PortInfo
MsgBox "This have been " & LastRow & " records.", vbInformation, "I'm done."