我正在浏览我们的代码库并看到很多像这样的测试:
declare @row_id int = ...
declare @row_attribute string
select
@row_attribute = ROW_ATTRIBUTE
from
SOME_TABLE
where
ROW_ID = @row_id
if @row_attribute is null
begin
... handle not existing condition
end
Run Code Online (Sandbox Code Playgroud)
这是问题,是否可以将if语句中的条件替换为:
if @@rowcount = 0
begin
... handle not existing condition
end
Run Code Online (Sandbox Code Playgroud)
我知道exist函数,但这里的目标是获取行的一些属性并同时检查它的存在.
是.
除非WHERE子句不在PK(或唯一索引)上,否则可能会返回多行,但无论如何这可能都是错误.在这种情况下,变量会被重复分配,其最终值将取决于计划.
DECLARE @row_attribute INT
select
@row_attribute = object_id
from
sys.objects /*<--No WHERE clause. Undefined what the
final value of @row_attribute will be.
depends on plan chosen */
SELECT @row_attribute, @@ROWCOUNT
Run Code Online (Sandbox Code Playgroud)
编辑.刚注意到你提出的测试if @@rowcount = 0不是 if @@rowcount <> 1这样,上面的内容不会影响它,整个答案可以简化为"是"!