【问题标题】:VBA ADODB - Get multiple rows affected from single queryVBA ADODB - 获取受单个查询影响的多行
【发布时间】:2013-01-15 16:03:28
【问题描述】:

我正在使用 VBA 的 ADODB 连接类通过 VBA 对 SQL Server 运行更新查询。在 SQL Server 中,查询返回受影响的行,可以通过 ADODB 命令类在 VBA 中访问这些行。

但是我不知道如何返回多个记录受影响语句的数组。

我正在使用示例代码:

Dim ADODBconn As ADODB.Connection
Dim rsRead As New ADODB.Recordset
Dim Rslt_Count As Long

'Set Up Connection and begin SQL Transaction
Set ADODBconn = CurrentProject.AccessConnection
ADODBconn.BeginTrans

'Build Update SQL
SQLLine = "******update query that runs on multiple tables here********"

'Execute SQL
ADODBconn.Execute SQLLine, Rslt_Count, dbFailOnError

MsgBox Rslt_Count
ADODBconn.CommitTrans
ADODBconn.Close

任何帮助表示赞赏。 谢谢 理查德

【问题讨论】:

    标签: vba adodb multiple-records


    【解决方案1】:

    假设你有一个存储过程:

    CREATE PROCEDURE UpdateTables
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
        DECLARE @RowCount2 INTEGER
        DECLARE @RowCount3 INTEGER
        DECLARE @RowCount4 INTEGER
    
        UPDATE Table2 Set atext = 'a' WHERE atext='b' 
        SELECT @RowCount2 = @@ROWCOUNT
        UPDATE Table3 Set atext = 'a' WHERE atext='b' 
        SELECT @RowCount3 = @@ROWCOUNT
        UPDATE Table4 Set atext = 'a' WHERE atext='b' 
        SELECT @RowCount4 = @@ROWCOUNT
    
        SELECT @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
    END
    

    根据Return number of rows affected by UPDATE statements

    另请参阅:access-SQL pass-through query (creating SP) error

    然后你可以:

    Dim dbconn As ADODB.Connection
    Dim cmd As New ADODB.Command
    Dim rs As New ADODB.Recordset
    Dim param As New ADODB.Parameter
    
    Set dbconn = New ADODB.Connection
    dbconn.ConnectionString = ServerConLocal
    
    dbconn.Open 
    
    Set cmd = New ADODB.Command
    cmd.ActiveConnection = dbconn
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "updatetables"
    
    rs.CursorType = adOpenStatic
    rs.CursorLocation = adUseClient
    rs.LockType = adLockOptimistic
    rs.Open cmd
    
    ''Records affected
    For Each fld In rs.Fields
        Debug.Print fld.Name & " : " & fld
    Next
    End Sub
    

    您也可以使用单行简单地创建传递查询:

    UpdateTables
    

    可能会返回:

        Table2  Table3  Table4
        0       2       0
    

    【讨论】:

    • 很棒的 SQL 技能。谢谢先生。
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2013-02-16
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多