在VBA中使用参数执行SQL存储过程

时间:2012-11-29 17:23:39

标签: stored-procedures excel-vba vba excel

我对此很新。我正在尝试在VBA中编写一个从excel执行存储过程并返回记录集的过程。它目前在电子表格2中返回存储过程的结果,但我不得不将参数硬编码到SQL代码中。以下是我从其他在线论坛上捏的内容。

Option Explicit

Public Sub OpenConnection()

'Set the variables
Dim conn As ADODB.Connection
Dim str As String
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim fld
Dim i As Integer

'Error handler
On Error GoTo errlbl

'Open database connection
Set conn = New ADODB.Connection

'First, construct the connection string.

'ODBC CONNECTION YOU'VE ALREADY SET UP:
conn.ConnectionString = "DSN=PC_Tool_Coding"

conn.Open       'Here's where the connection is opened.

Debug.Print conn.ConnectionString  'This can be very handy to help debug!

'Recordset
Set rs = New ADODB.Recordset

str = "exec Select_account_info"

'recordset is opened here
rs.Open str, conn, adOpenStatic, adLockReadOnly

If Not IsEmptyRecordset(rs) Then
    rs.MoveFirst

    'Populate the first row of the sheet with recordset’s field names
    i = 0
    For Each fld In rs.Fields
        Sheet2.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
        i = i + 1
    Next fld
    'Populate the sheet with the data from the recordset
    Sheet2.Range("A2").CopyFromRecordset rs


Else
    MsgBox "Unable to open recordset, or unable to connect to database.", _
       vbCritical, "Can't get requested records"

End If

'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

exitlbl:
  Debug.Print "Error: " & Err.Number
  If Err.Number = 0 Then
    MsgBox "Done", vbOKOnly, "All Done."
  End If
  Exit Sub
errlbl:
   MsgBox "Error #: " & Err.Number & ", Description:  " & Err.Description, vbCritical, "Error in OpenConnection()"
Exit Sub
'Resume exitlbl
End Sub

我已经四处寻找如何让它与参数一起工作,我似乎无法到达那里。我将使用的参数在SQL中称为@accgrpnum。它是一个12个字母的字符串。

非常感谢提前提供任何帮助。

1 个答案:

答案 0 :(得分:1)

看看bonCodigo的链接或

我也可以通过发送多个语句来执行此操作(使用SQL Server 2008),但在SQL语句中将其分开,如

str = "SET @accgrpnum = 'my_account'; exec Select_account_info;"