我必须管理一个日志,在其中必须查看事务插入的行数。有没有办法动态地做到这一点?
最佳答案
@@ ROWCOUNT将给出受影响的最后一个 SQL语句的行数,最好是在相关命令后将其捕获到局部变量中,因为它的值将在您下次查看时改变:
DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]
输出:
(2 row(s) affected)
Rows ROWCOUNT
----------- -----------
2 1
(1 row(s) affected)
您得到的
Rows
值为2,即插入的行数,但是ROWCOUNT为1,因为SELECT @Rows=@@ROWCOUNT
命令影响了1行如果您的事务中有多个INSERT或UPDATE等,则需要确定如何“计算”发生的情况。您可以为每个表分别设置总计,单个总计值或完全不同的值。您需要为每个要跟踪的总数选择一个DECLARE变量,并在对其应用的每个操作之后将其添加到该变量:
--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal int
DECLARE @PeachTotal int
SELECT @AppleTotal=0,@PeachTotal=0
BEGIN TRANSACTION
INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
COMMIT
SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal
关于sql-server - 如何获取事务插入的行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2272733/