views:

52

answers:

2

Hi, the question is hard to define without giving an example, e.g. I'd like to achieve something like this :

SELECT 
 (CASE WHEN ...) AS FieldA,
 20 + FieldA AS FieldB
FROM Tbl

Assuming that by "..." I've replaced a long and complex CASE statement, hence I don't want to repeat it when selecting FieldB and use the aliased FieldA instead.

IS THIS EVEN POSSIBLE? What could be a workaround? Note, that this will return multiple rows , hence the DECLARE/SET outside the SELECT statement is no good in my case.

PLEASE HELP.

P.S. I am using SQL 2008

+7  A: 

A workaroud would be to use a sub-query:

SELECT
  FieldA,
  FieldA + 20 AS FieldB
FROM (
  SELECT 
    (CASE WHEN ...) AS FieldA
  FROM Tbl
) t

To improve readability you could also use a CTE:

WITH t AS (
  SELECT 
    (CASE WHEN ...) AS FieldA
  FROM Tbl
)
SELECT
  FieldA,
  FieldA + 20 AS FieldB
FROM
  t
Peter Lang
or maybe a CTE to enhance readability.
JohnFx
@JohnFx: Good point, extended my answer.
Peter Lang
Personally I find the derived table easier to read, but that's just me.
HLGEM
+1  A: 

When I have complicated logic to compute a "virtual" column value from other column values in a table I generally create a single-table view of the original table with all the original columns plus the computed values as well. Then I do other SELECTs against the view. That allows me:

  1. To name my computed columns.

  2. To keep the logic for the computations in one place instead of scattered through various queries in the application.

Larry Lustig