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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nested IF in Select

Status
Not open for further replies.

sqlturbo

IS-IT--Management
Mar 11, 2002
67
US

Can I use a nested IF condition in a Select query? I want to query different columns in the same table depending on what is the value of the given attribute.

The psuedo code for the query looks like

Select colA, colB,
(If colC > 0 then colD
Else (if ColE>0 then ColF
Else (if ColG > 0 then ColH)))
From TableName.

Thanks.
 

try:

Select colA, colB,
case when colC > 0 then colD
Else ( case when ColE > 0 then ColF
Else (case when ColG > 0 then ColH end)
end)
end
From TableName.
 
i prefer not to nest them, it makes for cleaner sql

and i always code the "else null" because, well, just because

Code:
select colA
     , colB
     , case when colC > 0 then colD 
            when ColE > 0 then ColF 
            when ColG > 0 then ColH 
            else null
        end
  from TableName

rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (course starts January 9 2005)
 
rudy, the right answer was "just in case."
-Karl

[red] Cursors, triggers, user-defined functions and dynamic SQL are an axis of evil![/red]
[green]Life's uncertain...eat dessert first...www.deerfieldbakery.com[/green]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top