Below is a simplified version of SQL script I have. print @RowNum always shows 0, rather than the real record number of the first result set. What’s wrong? Thank you.
declare @i int, @RowNum int
set @i=0
while @i<2
begin
execute StoredProcedure @i --containing a big select
if @i=0 set @RowNum=@@rowcount
set @i=@i+1
end
print @RowNum
because this
if @i=0sets it to 0, even a print statement will set it to 0
now run this
here is another example
now it will be 0
PRINT also messes it up, this will be 2
this will be 0
I created a post with more examples and explanations here: When should you store @@ROWCOUNT into a variable?