views:

119

answers:

3

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
+9  A: 

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?

SQLMenace
anything after the result cause it to be reset, I also added an example with print, @@error has the same behavior
SQLMenace
Is it required behavior that ·if @i=0· affects @@rowcount value? You see I need the row number of the first result set. How can I achieve that?
phoenies
see modified code, if your else needs more than 1 statement then add BEGIN END around it
SQLMenace
Oh yes! You're so powerful, man. I love it!
phoenies
A: 

I'm gonna assume SQLMenace's answer is correct, but add, "Wouldn't this do what you want?":

    declare @RowNum int 
    execute StoredProcedure 0
    set @RowNum=@@rowcount 
    execute StoredProcedure 1 
    print @RowNum 
James Curran
The example code is inaccurate. What after `execute` is actually a dynamically generated string, which is very complicated. I really don't prefer to repeat the generating part of code.
phoenies
A: 

I would avoid this style in general. If you retrieve the number of rows selected from a table in the SP by querying @@rowcount after the call to the procedure, you are actually introducing an unnecessary dependency on how the procedure is implemented inside and compromise explicitness. If you later change the implementation of the procedure it may break the code outside and it would not be obvious while modifying the SP. You should instead use output parameter named appropriately.

vaso
You're right. The example code is inaccurate. It's a string rather than an SP in fact.
phoenies