Thursday 8 October 2015

Using @@ROWCOUNT ( System Variable)

Using @@ROWCOUNT ( System Variable)

@@ROWCOUNT  : It is a very useful system variable that returns the number of rows read/affected by the previous statement. It’s frequently used in loops and in error handling.

Remember that it returns the number of rows affected by the previous statement. Every statement. Look at this piece of code:

Example :
BEGIN TRY
    SELECT TOP 10 * FROM sys.objects
END TRY
BEGIN CATCH
    SELECT TOP 5 * FROM sys.objects
END CATCH
SELECT @@ROWCOUNT

You might think that the result of @@ROWCOUNT would be 10 since that’s the previous command that was run. You might also think it would be 5 since that’s the last command in the code, right? However you would be wrong on both counts. The TRY/CATCH block is actually the last command, so the result of @@ROWCOUNT is 0.

SELECT TOP 10 * FROM sys.objects
Select @@ROWCOUNT


In this case, the result of @@ROWCOUNT is 10.

No comments:

Post a Comment