我想查询SQL Server表并将该查询的结果存储在数组中。我只从一个字段返回Distinct()
所以它应该非常直接。我的语法产生错误
无效限定符
在这行代码Set r = conn.Execute
上突出显示单词conn
我应该如何重写此语法仍然使用ADO
但是能否成功运行此过程?
Public Function ReturnData()
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Dim f As ADODB.Field
Dim conn As String
Dim arrResults() As Variant
Set c = New ADODB.Connection
With c
.Provider = "sqloledb.1"
With .Properties
.Item("Data Source") = "ServerName"
.Item("Initial Catalog") = "Database"
.Item("PassWord") = "password"
.Item("User ID") = "user"
End With
.Open
Set r = conn.Execute("SELECT Distinct(Name) from registered where cancelled IS NULL;")
i = 0
r.MoveFirst
Do Until rst.EOF
arrResults(i) = rst.Fields(0)
i = i + 1
Loop
rst.Close
Set rst = Nothing
c.Close
End Function
答案 0 :(得分:1)
将记录集放入数组的另一种方法是使用Split
和Recordset.GetString
。无论如何它都避免了循环。这是一个例子。
Public Sub RsToArray()
Dim adoCon As ADODB.Connection
Dim adoRs As ADODB.Recordset
Dim vaLocations As Variant
Set adoCon = New ADODB.Connection
adoCon.Open sConn
Set adoRs = adoCon.Execute("SELECT DISTINCT LocationName FROM Locations")
vaLocations = Split(adoRs.GetString, vbCr)
Debug.Print Join(vaLocations, "|")
adoRs.Close
adoCon.Close
Set adoRs = Nothing
Set adoCon = Nothing
End Sub
答案 1 :(得分:0)
你有conn是一个字符串,c是连接 - 你可以做c.execute
尝试
Set r = c.Execute(...
我不确定你是否需要一个命令对象,如果你这样做,那么请看
https://msdn.microsoft.com/en-us/library/ms675065%28v=vs.85%29.aspx
了解如何为您的连接发出命令并执行它
无论如何,目前你正试图对字符串'执行' - 字符串是一种原始类型,并且不会在数据库上执行 - 我想你只是把c和conn混合起来 - 让我们知道它是怎么回事