【问题标题】:Proper syntax for exec of SQL Server stored procedure from within Excel 2007从 Excel 2007 中执行 SQL Server 存储过程的正确语法
【发布时间】:2012-09-14 21:41:40
【问题描述】:

让我们跳到连接属性的定义选项卡上的命令文本框......我的命令类型是 SQL。

我可以在 SSMS 中执行spDuplicatesAnalysis。我尝试了一些没有运气的事情,包括...

exec spDuplicatesAnalysis
dbo.spDuplicatesAnalysis

那么实际的命令 txt 应该如何读取呢?

谢谢!

【问题讨论】:

标签: sql sql-server excel stored-procedures


【解决方案1】:

从 Excel VBA 调用存储过程

  1. 打开一个新的 Excel 工作簿
  2. 将选项卡之一命名为“数据”(或更改以下代码)
  3. 打开 VB 编辑器 (Alt+F11)
  4. 添加新模块
  5. 设置对 Microsoft ActiveX 数据对象的引用(选择可用的最高版本号)
  6. 将以下代码添加到您的模块中

    Sub ExecStoredProcedureFromExcelVBA()
    
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connectString As String
    Dim custState As String
    Dim tgt As Worksheet
    
    Set tgt = ThisWorkbook.Sheets("Data")
    custState = "TX"
    
    ' Clear the target worksheet
    tgt.UsedRange.Clear
    
    ' Set the connection string
            connectString = "Provider=SQLOLEDB;Data Source=.;" & _
                 " Initial Catalog=Sandbox;Integrated Security = SSPI"
    
    ' Create the adodb objects
    Set cn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    
    ' Open the connection and execute the stored procedure
    cn.Open connectString
    cn.spGetCustomersForState custState, rs
    
    ' Check for results
    If rs.state = 1 Then
        If Not rs.EOF Then
            ' Write the contents of the recordset to our target
            tgt.Range("a1").CopyFromRecordset rs
        rs.Close
        End If
    End If
    
    ' Clean up after ourselves
    If CBool(cn.state And adStateOpen) Then cn.Close
    Set cn = Nothing
    Set rs = Nothing
    
    End Sub
    
  7. 修改模块以引用您要使用的数据库、存储过程和参数

  8. 运行代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多