Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return number of rows affected by UPDATE statements

Tags:

sql

sql-server

How can I get the number of rows affected by an UPDATE query in a Stored Procedure (SQL Server 2005), as a resultset. e.g.

CREATE PROCEDURE UpdateTables AS BEGIN     -- SET NOCOUNT ON added to prevent extra result sets from     -- interfering with SELECT statements.     SET NOCOUNT ON;      UPDATE Table1 Set Column = 0 WHERE Column IS NULL     UPDATE Table2 Set Column = 0 WHERE Column IS NULL     UPDATE Table3 Set Column = 0 WHERE Column IS NULL     UPDATE Table4 Set Column = 0 WHERE Column IS NULL END 

Then return:

Table1    Table2    Table3    Table4 32        45        0         3 
like image 867
SamWM Avatar asked Jul 09 '09 11:07

SamWM


People also ask

How do you get the number of rows affected by a query?

MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.

Which returns rows affected by a statement?

@@ROWCOUNT returns the affected rows from any statement, even if it's not DML or a SELECT query.

How do I return the number of rows affected by a stored procedure?

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.

Which method returns the number of rows affected by the execution of a query?

Get the Number of Rows Affected Using the execute() Method The execute() method executes the given SQL query, which may return multiple results.


1 Answers

CREATE PROCEDURE UpdateTables AS BEGIN     -- SET NOCOUNT ON added to prevent extra result sets from     -- interfering with SELECT statements.     SET NOCOUNT ON;     DECLARE @RowCount1 INTEGER     DECLARE @RowCount2 INTEGER     DECLARE @RowCount3 INTEGER     DECLARE @RowCount4 INTEGER      UPDATE Table1 Set Column = 0 WHERE Column IS NULL     SELECT @RowCount1 = @@ROWCOUNT     UPDATE Table2 Set Column = 0 WHERE Column IS NULL     SELECT @RowCount2 = @@ROWCOUNT     UPDATE Table3 Set Column = 0 WHERE Column IS NULL     SELECT @RowCount3 = @@ROWCOUNT     UPDATE Table4 Set Column = 0 WHERE Column IS NULL     SELECT @RowCount4 = @@ROWCOUNT      SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4 END 
like image 165
AdaTheDev Avatar answered Sep 23 '22 03:09

AdaTheDev