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=0
sets it to 0, even a print statement will set it to 0
now run this
declare @i int, @RowNum int
set @i=0
while @i<2
begin
if @i=0
begin
execute StoredProcedure @i --containing a big select
set @RowNum=@@rowcount
end
else
execute StoredProcedure @i
set @i=@i+1
end
print @RowNum
here is another example
select 1
union all
select 2
select @@rowcount --2
go
now it will be 0
select 1
union all
select 2
if 1=1
select @@rowcount --0
PRINT also messes it up, this will be 2
select 1
union all
select 2
select @@rowcount --2
go
this will be 0
select 1
union all
select 2
print '1'
select @@rowcount -- 0
I created a post with more examples and explanations here: When should you store @@ROWCOUNT into a variable?