简体   繁体   English

从 Excel 到 SQL 服务器的 ADO 连接执行但没有返回记录

[英]ADO connection from Excel to SQL Server executes but returns no records

I have a spreadsheet from which I want to pass SQL script to my SQL server Database, both to retrieve records and run stored procedures.我有一个电子表格,我想从中将 SQL 脚本传递给我的 SQL 服务器数据库,以检索记录和运行存储过程。

Here's my code:这是我的代码:

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

I feel like I'm missing something obvious.我觉得我错过了一些明显的东西。 I've searched this site and others, found examples where this code should work.我搜索了这个站点和其他站点,找到了该代码应该工作的示例。 I've tested the select statement in SSMS and it works as expected.我已经在 SSMS 中测试了 select 语句,它按预期工作。

Any help would be appreciated!任何帮助,将不胜感激!

The code that worked was from Mark Balhoff's comment.有效的代码来自 Mark Balhoff 的评论。 Here it is:这里是:

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

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

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