Avatar of garycris
garycris
Flag 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?
Microsoft SQL Server

Avatar of undefined
Last Comment
LandyJ

8/22/2022 - Mon
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
Sirees

Case statement evaluates a list of conditions and returns one of multiple possible result expressions.



ASKER CERTIFIED SOLUTION
dduser

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
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....
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
LandyJ

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

Select ISNULL(Sales, 0)
from Table1