Friday, March 23, 2012

How to reference a previous field Alias in TSQL as in Jet SQL?

My question is simple, I'd like to do something I do in Jet ANSI-89 SQL. Mind you I'm just adding numbers here - they are not actual columns in 'SomeTable'

SELECT 1 AS A, 2 AS B, A+B AS C
FROM SomeTable

The Jet engine evaluates and does arithmetic on the Aliased column names - handy when they contain their own functions. The resultset would show:

A B C
1 2 3

However from what I can tell SQL Server 2005 is not picking this up. Is their an equivalent?

The Jet syntax is non-standard SQL syntax so it will not work in SQL Server. You will have to use a derived table or CTE (in SQL Server 2005) or use a view or computed column in the table (if the expression involves columns from a single table).

select A, B, A+B as C

from (select 1 as A, 2 as B

from sometable

) as t

with t as (

select 1 as A, 2 as B

from sometable

)

select A, B, A+B as C

from t

No comments:

Post a Comment