• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 126
  • Last Modified:

SQL SELECT IF

Hi Experts,

How can I perform an IF statement within SELECT statement? For example, below I am trying to get an zero if it is NULL, otherwise get the actual value:

SELECT fldAgentID, 'prod1' AS product_id,
            IIF(fldFamRateprod1 IS NULL, 0, fldFamRateprod1)
FROM sometable
0
APD Toronto
Asked:
APD Toronto
2 Solutions
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Use the ISNULL function, which tests the first value to see if it's null, and if it is replace it with the second value.
SELECT fldAgentID, 'prod1' AS product_id, ISNULL(fldFamRateprod1,0) as fldFamRateprod1
FROM sometable 

Open in new window

COALESCE() also works if you want to have more than two arguments.

CASE blocks also work if you need more custom handling.  For more reading on CASE blocks check out my image and code-heavy article called SQL Server CASE Solutions.
0
 
PadawanDBAOperational DBACommented:
Try:

select
     fldAgentID,
     'prod1' as product_id,
     case
          when fldFamRateprod1 is null then 0
          else fldFamRateprod1
     end as fldFamRateprod1_scrubbed -- or whatever you want to name it
from
     sometable;     

Open in new window


Edit: Jim's is much more succinct and will actually perform better =)  And actually also made me think I should have done the original with a coalesce, which is another way to do it if you have multiple expressions and you want the first non-null value in an ordered list.  coalesce essentially creates a case =)  there have been some good EE posts around isnull vs. coalesce and isnull does perform better, it's just a T-SQL extension, not ANSI standard.  In interest of completeness, however:

select
     fldAgentID,
     'prod1' as product_id,
     coalesce( fldFamRateprod1, 0 ) as fldFamRateprod1_scrubbed -- or whatever you want to name it
from
     sometable;     

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now