Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the total rows affected by SQL Transaction

I have the following code in sql:

SET XACT_ABORT ON
Begin Transaction
INSERT INTO TABLE_A VALUES(/*Some Values*/)
INSERT INTO TABLE_B VALUES(/*Some Values*/)
INSERT INTO TABLE_C VALUES(/*Some Values*/)

Update Table Set Values A = A WHERE id = @id /* Some thing like that*/
Commit Transaction

So, i just wanted to know the total number of rows affected by in my Transaction Block of Insert and Updte statement

like image 295
HarshSharma Avatar asked Feb 17 '14 07:02

HarshSharma


People also ask

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

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. Show activity on this post. @@RowCount will give you the number of records affected by a SQL Statement.

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.

Which function will return the number of rows affected by a query?

To overcome this issue, SQL Server introduces the ROWCOUNT_BIG system function, which returns the number of rows affected by a specific query in the BIGINT data type.


1 Answers

You can use @@ROWCOUNT variable

To get Inserts + all affected rows of update , declare a variable and store rowcount values in it.

DECLARE @totalRows INT
SET @totalRows = 0
INSERT INTO TABLE_A VALUES(/*Some Values*/)
SET @totalRows =@totalRows + @@ROWCOUNT

INSERT INTO TABLE_B VALUES(/*Some Values*/)
SET @totalRows =@totalRows + @@ROWCOUNT

INSERT INTO TABLE_C VALUES(/*Some Values*/)
SET @totalRows =@totalRows + @@ROWCOUNT

Update Table Set Values A = A WHERE id = @id /* Some thing like that*/
SET @totalRows =@totalRows + @@ROWCOUNT

SELECT @totalRows As TotalRowsAffected
like image 170
Mudassir Hasan Avatar answered Oct 25 '22 21:10

Mudassir Hasan