如何在Microsoft Excel中执行存储的SQL过程?


Answers:


5

这是VBA中ADODB连接的作业。这是一个带有简单SELECT查询示例代码的链接,但这也将处理存储过程。

http://www.ozgrid.com/forum/showthread.php?t=83016&page=1

关键项目申报的需要ADODB.ConnectionADODB.Recordset和匹配您的数据库连接字符串。打开连接后,使用如下语法(从链接中获取)执行SQL语句:

With cnt 
    .CursorLocation = adUseClient 
    .Open stADO    // stADO is the connection string.
    .CommandTimeout = 0 
    Set rst = .Execute(stSQL) 
End With

然后使用将记录集(rst,上面)中的数据移动到一个范围内Range.CopyFromRecordSet


1

我不确定Excel的最新版本,但在2000年和2003年,您只能访问一个视图并将其数据显示在Excel工作表上。

存储过程的主要优点是能够参数化结果,但为此您需要某种UI,并且在首次在excel中定义之后,您需要一种以编程方式修改查询定义的方法。我们没有找到这样做的方法,但是使用视图为我们需要做的事情提供了足够的功能。


1

这个VBA与@Excellll的答案非常相似,我在自己的工作中使用它很有效。

使用这个小实用功能:

Public Function IsEmptyRecordset(rs As Recordset) As Boolean
     IsEmptyRecordset = ((rs.BOF = True) And (rs.EOF = True))
End Function

然后这是一个重要的功能(我为看起来很糟糕的段落对齐道歉):

Option Explicit

Public Sub OpenConnection()
Dim conn As ADODB.Connection
Dim str As String
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim myPath
Dim fld
Dim i As Integer

On Error GoTo errlbl


'Open database connection
Set conn = New ADODB.Connection

'First, construct the connection string.

'NOTE:  YOU CAN DO THIS WITH A STRING SPELLING OUT THE ENTIRE CONNECTION...
'conn.ConnectionString = _
'    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
'    "Data Source=" & _
'    myPath & "\ConnectionTest.mdb"

'...OR WITH AN ODBC CONNECTION YOU'VE ALREADY SET UP:
conn.ConnectionString = "DSN=myDSN"

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

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

Set rs = New ADODB.Recordset
'Construct string.  This can "Select" statement constructed on-the-fly,
'str = "Select * from vwMyView order by Col1, Col2, Col3"  
'or an "Execute" statement:
str = "exec uspMyStoredProc"

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

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
        Sheet1.Cells(1, i + 1).Value = rs.Fields.Item(i).Name
        i = i + 1
    Next fld
    'Populate the sheet with the data from the recordset
    Sheet1.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 "All data has been pulled and placed on Sheet1", 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

希望这可以帮助。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.