views:

38

answers:

4

What would be the best way of doing this?

select 'blah' as foo,
        CASE 
          WHEN foo='blah' THEN 'fizz'
          ELSE 'buzz'
        END as bar

As it is written right now I get an invalid column name 'foo' error. Is there anyway to do this where the select statement could be used as a view?

+1  A: 

You can use a derived table if you don't want to repeat the column definition.

select   case when foo='blah'
  then 'fizz'
  else 'buzz' 
end as bar
FROM
(
select 'blah' as foo
) derived

Or a CTE

;
With blahs As
(
select 'blah' as foo
)


select   case when foo='blah'
  then 'fizz'
  else 'buzz' 
end as bar
FROM blahs

A quick test shows the execution plan for all three versions below are the same

SELECT foo,
       CASE
              WHEN foo='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   ( SELECT
               CASE
                       WHEN [number] % 5 = 0
                       THEN 'blah'
                       ELSE 'notblah'
               END AS foo
       FROM    [master].[dbo].[spt_values]
       )
       D ;


WITH blahs AS
     ( SELECT
             CASE
                     WHEN [number] % 5 = 0
                     THEN 'blah'
                     ELSE 'notblah'
             END AS foo
     FROM    [master].[dbo].[spt_values]
     )
SELECT foo,
       CASE
              WHEN foo='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   blahs


SELECT
       CASE
              WHEN [number] % 5 = 0
              THEN 'blah'
              ELSE 'notblah'
       END AS foo,
       CASE
              WHEN
                     CASE
                            WHEN [number] % 5 = 0
                            THEN 'blah'
                            ELSE 'notblah'
                     END='blah'
              THEN 'fizz'
              ELSE 'buzz'
       END AS bar
FROM   [master].[dbo].[spt_values]
Martin Smith
+2  A: 

You need to use a nested select like this:

select foo,
  case when foo='blah'
  then 'fizz'
  else 'buzz'
  end as bar
from ( select 'blah' as foo ) a

The problem is that the column foo is not recognized by the name in the same select statement.

Jose Chama
A: 

You could possibly use a table query like so:

select a.foo,
  case when a.foo = 'blah'
  then 'fizz'
  else 'buzz'
  end as bar
from (select 'blah' as foo) a
Fosco
A: 
WITH TmpTbl as (SELECT 'blah' as foo)
SELECT foo, CASE WHEN foo='blah' THEN 'fizz' 
            ELSE 'buzz' 
            END as bar FROM TmpTbl
Baaju