我正在从VBA调用PC上的存储过程,它工作正常。在另一台PC和其他用户中,它不起作用。不过,只有一个查询,它可以在两台PC上使用。
我正在按如下方式调用存储过程:
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
' Connection string for accessing MS SQL database
ConnectionString = <Connection details>
' Opens connection to the database
cnn.Open ConnectionString
' Timeout error in seconds for executing the entire query; The stored procedure normally runs for around 20 min
cnn.CommandTimeout = 2400
' Process execution
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn
rst.Close
我猜我在执行存储过程时会收到一条错误消息,但是我不知道如何捕获它。
我尝试了以下操作,但没有任何输出
' Process execution
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn
Debug.Print rst.Fields.Count
Debug.Print rst.RecordCount
Debug.Print rst
rst.Close
当我在SQL Management Studio中运行存储过程时,由于存储过程只是更新表,因此我只会得到输出消息。喜欢:
(29145907 rows affected)
(330527 rows affected)
我也尝试在链接here之后添加错误信息,但是该过程在运行时没有给我任何错误。喜欢:
' Process execution
DateSelection = Sheets("STB Check").Range("F1")
'StrQuery = "exec [00_Main] @date = '" & DateSelection & "' "
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn
Done:
rst.Close
Exit Sub
AdoError:
Dim errLoop As Error
Dim strError As String
i = 1
' Process
StrTmp = StrTmp & vbCrLf & "VB Error # " & Str(Err.Number)
StrTmp = StrTmp & vbCrLf & " Generated by " & Err.Source
StrTmp = StrTmp & vbCrLf & " Description " & Err.Description
' Enumerate Errors collection and display properties of
' each Error object.
Set Errs1 = cnn.Errors
For Each errLoop In Errs1
With errLoop
StrTmp = StrTmp & vbCrLf & "Error #" & i & ":"
StrTmp = StrTmp & vbCrLf & " ADO Error #" & .Number
StrTmp = StrTmp & vbCrLf & " Description " & .Description
StrTmp = StrTmp & vbCrLf & " Source " & .Source
i = i + 1
End With
Next
MsgBox StrTmp
' Clean up Gracefully
On Error Resume Next
GoTo Done
有什么想法吗?
答案 0 :(得分:2)
使用适当的参数设置,并将日期视为Date
,而不是字符串。
使用ADODB.Recordset
代替直接运行ADODB.Command
;将命令文本设置为仅存储过程的名称,并向其ADODB.Parameter
集合中添加一个Parameters
,提供单元格值(在验证IsDate
返回True
之后该单元格的值)-like on docs.microsoft.com:
Dim theDate As Date
theDate = Sheets("STB Check").Range("F1").Value
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "[00_Main]"
Dim dateParam As ADODB.Parameter
Set dateParam = cmd.CreateParameter("date", adDate, adParamInput)
dateParam.Value = theDate
cmd.Parameters.Append dateParam
Dim results As ADODB.Recordset
Set results = cmd.Execute