返回受SQL Transaction影响的总行数

时间:2014-02-17 07:37:29

标签: sql sql-server tsql

我在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

所以,我只是想知道我的Insert和Updte语句的事务块中受影响的总行数

1 个答案:

答案 0 :(得分:11)

您可以使用@@ROWCOUNT变量

要获取Inserts +所有受影响的更新行,请声明一个变量并在其中存储rowcount值。

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