How can I get the number of records affected by a stored procedure?

前端 未结 6 1972
轮回少年
轮回少年 2020-12-04 20:32

For INSERT, UPDATE and DELETE SQL statements executed directly against the database, most database providers return the count of rows

相关标签:
6条回答
  • 2020-12-04 21:13

    @@ROWCOUNT

    0 讨论(0)
  • 2020-12-04 21:19

    @@RowCount will give you the number of records affected by a SQL Statement.

    The @@RowCount works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.

    SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR
    

    If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.

    SELECT @NumRowsChanged = @NumRowsChanged  + @@ROWCOUNT, @ErrorCode = @@ERROR
    
    0 讨论(0)
  • 2020-12-04 21:20

    WARNING: @@ROWCOUNT may return bogus data if the table being altered has triggers attached to it!

    The @@ROWCOUNT will return the number of records affected by the TRIGGER, not the actual statement!

    0 讨论(0)
  • 2020-12-04 21:21

    For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

    0 讨论(0)
  • 2020-12-04 21:28

    Register an out parameter for the stored procedure, and set the value based on @@ROWCOUNT if using SQL Server. Use SQL%ROWCOUNT if you are using Oracle.

    Mind that if you have multiple INSERT/UPDATE/DELETE, you'll need a variable to store the result from @@ROWCOUNT for each operation.

    0 讨论(0)
  • 2020-12-04 21:28

    Turns out for me that SET NOCOUNT ON was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery(); always returned -1.

    I just set it off: SET NOCOUNT OFF without needing to use @@ROWCOUNT.

    More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete

    0 讨论(0)
提交回复
热议问题