【发布时间】:2021-12-15 16:48:58
【问题描述】:
我有一个电子表格,我想从中将 SQL 脚本传递到我的 SQL 服务器数据库,以检索记录和运行存储过程。
这是我的代码:
Sub ApendPickListData()
Dim SqlConn As New ADODB.Connection
Dim listID As Integer
Dim lists As New ADODB.Recordset
Dim SQLstr As String
SqlConn.ConnectionString = "Provider = 'SQLOLEDB';Server=MyServer\SQLEXPRESS;Database=MyDatabase;Uid=Username;PWD=Password;"
SqlConn.Open
'The following execution of a stored procedure works
SqlConn.Execute "Exec spListsInsertNew @Type = 'Picking', @Date ='" & Date & "'"
SQLstr = "SELECT ItemList.ItemNumber from ItemList"
'This method doesn't work
With lists
.ActiveConnection = SqlConn
.Source = SQLstr
.Open
Debug.Print .RecordCount
'prints -1 in the immediate window - no records
End With
'Neither does this method
Set lists = SqlConn.Execute(SQLstr)
Debug.Print lists.RecordCount
'prints -1 in the immediate window - no records
SqlConn.Close
End Sub
我觉得我错过了一些明显的东西。我搜索了这个站点和其他站点,找到了该代码应该工作的示例。我已经在 SSMS 中测试了 select 语句,它按预期工作。
任何帮助将不胜感激!
【问题讨论】:
-
如果您正确地为您的查询设置参数,它会起作用吗?
-
原谅我的无知,但是如何正确参数化不带参数的选择查询?
-
Exec spListsInsertNew @Type = 'Picking', @Date ='" & Date & "'"有 2 个参数,您正在注入其中一个。 -
RecordCount在使用默认游标打开记录集后不可靠。有几种方法,但我最常用的一种是.MoveLast,然后是.MoveFirst,然后是.RecordCount,然后开始处理记录。我相信您也可以通过使用.CursorLocation = <some constant>之类的设置客户端光标来修复它。 -
在打开记录集之前尝试设置
.CursorLocation = adUseClient。
标签: sql-server excel ado