views:

49

answers:

3

Hi, I'm here again-

I have something like this

Select A.a, A.b, A.a+A.b as c, (A.a+A.b*2)+A.d as d from Table

But i want to know, if it is possible, to make it work with something like this:

Select A.a,A.b,A.a+A.b as c, (c*2)+A.d as d from Table

Thank you

+3  A: 

No, you cannot do that, but your best bet is to use computed column

@pojomx:

You can use computed column if you don't want to keep computing values in query:

example:

create table orders
(
product varchar(50) not null,
qty int not null,
unit_price money not null,
amount as qty * unit_price persisted
);

insert into orders(product,qty,unit_price) values('KEYBOARD',5, 20);

select * from orders;

Output:

product    qty    unit_price   amount
KEYBOARD   5      20.00        100.00
Michael Buen
I guess that makes sense... you can't have self-referential definitions in column definitions...
sheepsimulator
XD fail, then, what are computed columns? x)
pojomx
thanks for the info :)
pojomx
+3  A: 

The column alias are not available in other columns of the select. You could rewrite using an inline view:

select a, b, c, (c*2)+d as d
from (select A.a, A.b, A.a+A.b as c, A.d as d from Table A) table_alias_for_view
Shannon Severance
I was thinking on this... thank you =)
pojomx
+1  A: 

not in SQL Server, you must do like in your first example:

Select A.a, A.b, A.a+A.b as c, (A.a+A.b*2)+A.d as d from Table

or use a derived table like:

SELECT
    dt.a, dt.b,dt.c, dt.c*2+dt.a as d
    FROM (Select 
              A.a, A.b, A.a+A.b as c
              from Table
         ) dt
KM