SQL Server - 在多线程应用程序中使用@@ROWCOUNT 安全吗? [英] SQL Server - is using @@ROWCOUNT safe in multithreaded applications?

查看:19
本文介绍了SQL Server - 在多线程应用程序中使用@@ROWCOUNT 安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 SQL Server 2008.

I am using SQL Server 2008.

我有一个表 A,它在一秒钟内接受许多插入/更新.插入后,更新我想获取受影响的行数.

I have a table A which accepts many insert/update in one seconds. After insert, update I want to get the number of rows affected.

INSERT INTO A (ID) VALUES (1)
IF @@ROWCOUNT = 0
    PRINT 'NO ROWS AFFECTED'

在执行查询时,应用程序可能会再次调用相同的查询.那么如果当前执行在 INSERT 之后但在 IF 块之前会发生什么.

While query is being executed, the same query may be called again by application. So what happens if the current execution is after INSERT but before IF block at that moment.

您是否认为 @@ROWCOUNT 可能会因此而给出错误的结果?

Do you think @@ROWCOUNT may give wrong result for that reason?

或者它在它的上下文中总是安全的?

Or is it always safe in its context?

推荐答案

是的 - 它是安全的.它总是引用当前查询中的前一个操作

Yes - its safe. It always refers the previous operation in current query

但是

如果您想知道受影响的行数,请先将其保存到变量中,因为在 IF 语句之后计数 @@ROWCOUNT重置

if you want to know the number of rows affected, save it to variable first, because after IF statement the count @@ROWCOUNT resets

INSERT INTO A (ID) VALUES (1)
DECLARE @rc INT = @@ROWCOUNT
IF @rc = 0
    PRINT 'NO ROWS AFFECTED'
ELSE
  SELECT @rc AS RowsAffected

这篇关于SQL Server - 在多线程应用程序中使用@@ROWCOUNT 安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆