0

How can I avoid the if/else please? The 'Active' column can not be null in the table.

CREATE   procedure spExample(@bitActive bit)
as

if @bitActive is not null
    select      a.PKID 
    from        Alerts a 
    where       a.Active = @bitActive
else
    select      a.PKID 
    from        Alerts a 

2 Answers 2

3

Or, you could go with

select      a.PKID 
from        Alerts a 
where       ISNULL(@bitActive, a.Active) = a.Active

This is essentially the same as the preceding answer, but avoids using an OR in the Where.

I should point out that you may well get better performance using your current code, as it avoids executing the IS NULL test on every row. If you are using indexes on your data, the IS NULL test may mean that your database engine's query optimiser cannot use the indexes which may produce a sub-optimal execution path.

I can tell you from experience that we have seen significant improvement (mins to seconds) by removing the ISNULL checks and writing SQL that is specific to the parameters either by using IF statements or dynamic SQL.

We are using Sql Server 2008, so your mileage may vary if you use another engine. I suggest you do some tests to see if there are any performance issues on your database.

Cheers, Dean.

1
  • 3
    On SQL Server 2008 OPTION (RECOMPILE) can help the @bitActive IS NULL OR a.Active = @bitActive pattern but not the ISNULL(@bitActive, a.Active) = a.Active one as discussed here Oct 10, 2011 at 21:47
1
select      a.PKID 
from        Alerts a 
where       @bitActive IS NULL OR a.Active = @bitActive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.