【问题标题】:ADO connection from Excel to SQL Server executes but returns no records从 Excel 到 SQL Server 的 ADO 连接执行但不返回任何记录
【发布时间】: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


【解决方案1】:

有效的代码来自 Mark Ba​​lhoff 的评论。这里是:

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=MyDB;Uid=Username;PWD=Password;"
SqlConn.Open


SQLstr = "select dbo.ItemList.ItemNumber from dbo.ItemList"

With lists
.ActiveConnection = SqlConn
.Source = SQLstr
.CursorLocation = adUseClient 'This was the key!
.Open
Debug.Print .RecordCount

End With

SqlConn.close
End Sub

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2013-05-11
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多