views:

57

answers:

4

In a query, I have a column like this:

case when X = 1 then
  case when Y <> 0 then YY else XX end
    else ZZ
end as MyColumn

Is there a way, in another column, to check the above column value referencing MyColumn instead of rewriting the case statement?

I should value another column based on the MyColumn value.

Thanks

+3  A: 

No, not without either:

  • duplicating the logic in subsequent columns
  • doing the initial CASE evaluation in a derived table/inline view:

    SELECT aa.mycolumn,
           CASE 
             WHEN aa.mycolumn = ? THEN ....
           END AS next_mycolumn_evaluation
      FROM (SELECT CASE
                     WHEN X = 1 THEN
                      CASE WHEN Y <> 0 THEN YY 
                        ELSE XX END
                     ELSE ZZ 
                   END AS mycolumn
              FROM ...) aa
    
OMG Ponies
Unfortunately my query is a View, so I think I have to duplicate the logic. Thanks for your answer.
opaera
@opeara: SQL Server allows derived tables/inline views in views
OMG Ponies
Ah, cool, I would try, but sorry, I don't understand cleary your code. I'll google Inline Views by the way, many thanks.
opaera
I got it thanks! About performances, there are particular differences between the 2 ways to do this?
opaera
@opeara: Derived tables/inline views are commonly referred to as subqueries, but I disagree with that terminology.
OMG Ponies
@opeara: Performance wise, a single pass is better than using a derived table/inline view, assuming it's possible.
OMG Ponies
@opaera: Don't forget to mark answer an answer - see [this link for details](http://meta.stackoverflow.com/questions/5234)
OMG Ponies
A: 

If I understand you correctly, (and I may not), (ssuming X, Y, XX, YY, and ZZ are other columns in this table), you could create a calculated column on this table, that ues this expression as it's formula ..

Alter Table TableName Add NewColumn 
   as Case when X = 1 then
       Case when Y <> 0 YY else XX end
       else ZZ end 
Charles Bretana
A: 

You could probably do it with subqueries. For example:

Select someTable.ID, someTable.A, someTable.B,
    case subT.myColumn = 0 then 'BLARG' else 'huh?' end As outerMyColumn
from someTable,
    (Select ID, case when X = 1 then
      case when Y <> 0 YY else XX end
        else ZZ
    end as MyColumn
    From someTable
    where someCondition) subT
where subT.ID = someTable.ID;
FrustratedWithFormsDesigner
A: 

You can Write like that case when X = 1 and Y <> 0 then YY When X = 1 and Y = 0 then XX else ZZ end end as MyColumn

there is only one case in this.

KuldipMCA