I am going through our codebase and see a lot of tests like this:
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
Here is the question, is it OK/not OK to replace the condition in if statement to:
if @@rowcount = 0
begin
... handle not existing condition
end
I know about exist function, but the goal here is to get some attributes of the row and check for its existence at the same time.
Yes.
Except if the
WHEREclause isn’t on a PK (or unique index) more than one row might be returned but that would probably be an error anyway. In that eventuality the variable is repeatedly reassigned to and its final value will depend on the plan.Edit. Just noticed your proposed test is
if @@rowcount = 0notif @@rowcount <> 1so the above wouldn’t affect it and the whole answer could be condensed to the word “Yes”!