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
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.
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:
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With