问题描述
我正在使用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安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!