Daily Archives: 01/19/2012

@@ROWCOUNT is affected by IF statement

Let’s say you’re writing T-SQL code and need to make sure that your query returns one and only row. If no records returned – an error message needs to be shown. If more than one record is returned – another error message needs to be show. The code goes something like this:

-- ... query runs here and returns row

IF @@ROWCOUNT = 0 RAISERROR('No records found', 18, 1)
ELSE IF @@ROWCOUNT > 0 RAISERROR('More than one record found', 18, 1)

-- ... continue when exactly one row is returned

Now if your query returns 3 records you’d expect it to trip the second IF statement and raise error with correct message. Unfortunately this doesn’t happen. The reason being – the first IF statement resets @@ROWCOUNT to 0. So, to avoid this we need to preserve the @@ROWCOUNT value in a local variable:

DECLARE @iRowCount int

-- ... query runs here and returns row

SET @iRowCount = @@ROWCOUNT

IF @iRowCount = 0 RAISERROR('No records found', 18, 1)
ELSE IF @iRowCount > 0 RAISERROR('More than one record found', 18, 1)

-- ... continue when exactly one row is returned

This way count of rows returned by the query is saved and is not affected by any following statements.