Link to home
Start Free TrialLog in
Avatar of garycris
garycrisFlag for United States of America

asked on

Can you use IF in SQL query

Is there a way to use IF in a SQL query or do you have to use CASE?
Avatar of Sirees
Sirees

You can use if statement  to test for a condition

From BOL:

IF (@ErrorSaveVariable <> 0)
BEGIN
   PRINT 'Errors encountered, rolling back.'
   PRINT 'Last error encountered: ' +
      CAST(@ErrorSaveVariable AS VARCHAR(10))
   ROLLBACK
END
ELSE
BEGIN
   PRINT 'No Errors encountered, committing.'
   COMMIT
END
RETURN @ErrorSaveVariable
Case statement evaluates a list of conditions and returns one of multiple possible result expressions.



ASKER CERTIFIED SOLUTION
Avatar of dduser
dduser

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of garycris

ASKER

Let me clarify,

I just want to run a simple SELECT query and I want to know if I can use IF or if I can only use CASE

For example, this works fine:

SELECT
     CASE WHEN [Sales] IS NULL THEN 0 ELSE [Sales] END as Expr1
FROM TABLE1

If I try
SELECT
     IF [Sales] IS NULL
          THEN 0
          ELSE [Sales]
     END IF AS Expr1
FROM TABLE1

I get an error....
In this instance, you can't use IF.   You want to use ISNULL instead:

Select ISNULL(Sales, 0)
from Table1