Excel VBA执行SQL Server存储过程 - 结果集抛出错误3704

时间:2013-08-28 12:37:56

标签: sql sql-server excel vba stored-procedures

我正在尝试从Excel VBA执行SQL Server存储过程。该过程将行返回到结果集对象中。但是,在运行代码时,它会引发错误:

  

3704关闭对象时不允许操作

注意:
数据库连接没有问题,因为在同一连接对象上运行的Select查询工作正常。

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rst As New ADODB.Recordset

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
ThisWorkbook.initialize
cn.Provider = "sqloledb"
cn.Properties("Data Source").Value = ThisWorkbook.server
cn.Properties("Initial Catalog").Value = ThisWorkbook.db
cn.Properties("User ID").Value = "xxxxx"
cn.Properties("Password").Value = "xxxxx"
cn.Open

Set cmd = New ADODB.Command
cmd.CommandText = "Generate_KPI_Process_Quality_Check_RunTime"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = cn

Set prm = cmd.CreateParameter("@currentMonth", adChar, adParamInput, 255, cmb_month.Value)
cmd.Parameters.Append prm

Set prm = cmd.CreateParameter("@center", adChar, adParamInput, 255, cmb_center.Value)
cmd.Parameters.Append prm

rst.CursorType = adOpenStatic
rst.CursorLocation = adUseClient
rst.CursorLocation = adUseServer
rst.LockType = adLockOptimistic

rst.Open cmd

If (rst.BOF And rst.EOF) Then
'Some Code
End If

4 个答案:

答案 0 :(得分:2)

SET NOCOUNT ON

在存储过程中 - 这将阻止输出文本生成,如“1记录已更新”。

答案 1 :(得分:1)

您必须为Recordset Object

Open方法提供更多参数

尝试rst.Open cmd, cn

答案 2 :(得分:1)

使用Set关键字分配对象:

Set cmd.ActiveConnection = cn

否则,将分配Connection对象的默认属性(恰好是连接字符串)来代替Connection对象本身。

答案 3 :(得分:0)

只需添加另一个包含结果集的记录集

Dim rst1 As New ADODB.Recordset
SET rst1=rst.NextRecordset 'this will return the first resultset

If rst1.BOF or rst1.EOF Then...
    'some code
End If