我在这里使用VBA中带参数的存储过程苦苦挣扎。下面的代码没有参数工作正常,但参数不起作用。
我的代码:
Sub CopyDataFromDatabase()
Dim Conn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim Fields As ADODB.Field
Dim Cmd As ADODB.Command
Set Conn = New ADODB.Connection
Set Cmd = New ADODB.Command
Set Rs = New ADODB.Recordset
Conn.Open "My connection string here--------"
Cmd.CommandType = adCmdStoredProc
Cmd.Parameters.Append Cmd.CreateParameter("@Division", adVarChar, adParamInput, 40)
Cmd.Parameters("@Division").Value = "South"
Cmd.Parameters.Append Cmd.CreateParameter("@Area", adVarChar, adParamInput, 40)
Cmd.Parameters("@Area").Value = "IT"
Cmd.CommandText = "My SP here------"
Set Rs = Cmd.Execute
On Error GoTo CloseRecordset
Worksheets.Add
For Each Fields In Rs.Fields
ActiveCell.Value = Fields.Name
ActiveCell.Font.Bold = True
ActiveCell.Font.Underline = True
ActiveCell.HorizontalAlignment = xlCenter
ActiveCell.Interior.Color = RGB(0, 128, 255)
ActiveCell.Font.Color = RGB(255, 255, 255)
ActiveCell.Offset(0, 1).Select
Next Fields
Range("A1").Select
Range("A2").CopyFromRecordset Rs
CloseRecordset:
Rs.Close
Set Rs = Nothing
Set Cmd = Nothing
CloseConnection:
Conn.Close
Set Conn = Nothing
End Sub
当我跑步时,它没有给出任何错误,只显示执行但没有结果
有人能说出我做错的地方吗?感谢
答案 0 :(得分:1)
我已经成功声明了一个变量数组并将参数(按顺序!)填充到该数组中,然后将数据传递给execute方法以执行存储过程。
假设你的存储过程需要'Division'然后'Area',这样的事情就可以解决问题了:
Sub CopyDataFromDatabase()
Dim Conn As ADODB.Connection
Dim Rs As ADODB.Recordset
Dim Fields As ADODB.Field
Dim Cmd As ADODB.Command
'New variable
Dim v_Params(1 To 2) As Variant 'assuming you have 2 parameters
Set Conn = New ADODB.Connection
Set Cmd = New ADODB.Command
Set Rs = New ADODB.Recordset
Conn.Open "My connection string here--------"
v_Params(1) = "South"
v_Params(2) = "IT"
With Cmd
.ActiveConnection = Conn
.CommandType = adCmdStoredProc
.CommandText = "My SP here------"
.CommandTimeout = 0
Set rs = .Execute(, v_Params)
End With
看看是否有效,因为我目前正在成功使用此方法。我没有看到需要修改子程序的其余部分。
我使用With Cmd
和End With
来避免每次完全限定引用。
该问题的作者发现的问题是SP在参数传递给它时超时。决议是将CommandTimeout
属性设置为0。