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

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

如何在 Microsoft Excel 中执行存储过程并获取其返回的所有数据?

答案1

这是 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

答案2

我不确定 Excel 的最新版本,但在 2000 年和 2003 年,您所能做的就是访问视图并将其数据显示在 Excel 表上。

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

答案3

这个 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

希望这可以帮助。

相关内容