Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CASE or IF ELSE Logic Question

Status
Not open for further replies.

larrydavid

Programmer
Jul 22, 2010
174
US
Hello, I have a stored proc with case statements where there are two conditions which is covered by a regular CASE statement:
[TableValue1] = CASE
WHEN Value1 IS NOT NULL THEN Value1
ELSE null
END

But now I have a situation where it can be any of three possible conditions:
CASE WHEN Value1 IS NOT NULL THEN Value1
CASE WHEN Value2 IS NOT NULL THEN Value2
CASE WHEN Value3 IS NOT NULL THEN Value3
ELSE null
END

I'm not quite sure how to approach this, because Value 2 can supercede Value1, Value3 can supercede Value 2 and so forth. Can I assume that if I use the fields as they are being selected in ascending order that this order of precendence would happen anyway? Or, do I need to implement nested CASE statements for this to happen the right way? If so, is there an IF-THEN-ELSEIF type of construct I can apply in SQL Server 2005 in a stored proc? I've researched this and see this in SQL Server 2008 but not in SQL Server 2005.

Any help would be most greatly appreciated.

Thanks,
Larry
 
the if-then-else structure you are looking for is the CASE structure :)
Code:
[result] = 
   CASE WHEN Value1 IS NOT NULL THEN Value1 
        WHEN Value2 IS NOT NULL THEN Value2 
        WHEN Value3 IS NOT NULL THEN Value3
        ELSE null
    END

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top