Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get the @@rowcount value?

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
like image 848
phoenies Avatar asked Aug 26 '10 14:08

phoenies


People also ask

How do I set the value in @@rowcount in Transact-SQL?

Transact-SQL statements can set the value in @@ROWCOUNT in the following ways: Set @@ROWCOUNT to the number of rows affected or read. Rows may or may not be sent to the client. Preserve @@ROWCOUNT from the previous statement execution.

What is @@rowcount in SQL Server?

The statement can be anything that affects rows: SELECT, INSERT, UPDATE, DELETE and so on. It’s important that @@ROWCOUNT is called in the same execution as the previous query. Suppose I would run the SELECT statement first from the previous example, and then run SELECT @@ROWCOUNT separately. This will return 1 instead of 1,000 as shown below:

How do I access @@rowcount in an IF statement?

You can access @@ROWCOUNT like any other variable in an IF statement. For example: In this script, we perform an UPDATE statement. After the statement is done, we check if any rows were updated at all.

How do I reset the rowcount value to 0?

DECLARE CURSOR and FETCH set the @@ROWCOUNT value to 1. EXECUTE statements preserve the previous @@ROWCOUNT. Statements such as USE, SET <option>, DEALLOCATE CURSOR, CLOSE CURSOR, PRINT, RAISERROR, BEGIN TRANSACTION, or COMMIT TRANSACTION reset the ROWCOUNT value to 0. Natively compiled stored procedures preserve the previous @@ROWCOUNT.


1 Answers

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?

like image 81
SQLMenace Avatar answered Sep 27 '22 23:09

SQLMenace