I’ve worked a bit with MS Access, but I’m no expert on SQL Server. And now I’ve found a difference that puzzles me. (I’m using SQL Server 2008.)
I’m doing some calculations in a SELECT, and want to use the result from one calculation in the next one.
Let’s say we have a table Products with two fields – Name and Price. In MS Access, this query works fine:
SELECT Name, Price * 2 AS DoublePrice, DoublePrice * 2 AS QuadPrice
FROM Products
I.e. I use the result of the first calculation in the next. This gives the result I expect – name + double the price + four times the price.
But this won’t compile under SQL Server – I get an “unknown field: DoublePrice”-error in the second calculation.
Is there any way to make this work? I.e. to use a (named) calculation later in the same SELECT? I do some pretty large calculations and want to build on those values in other calculations. And it feels stupid to add an extra view/sub-SELECT just for that…
Grateful for any help! 🙂
Nope, not directly. Either you use a derived table, a CTE, a
CROSS APPLYor even the calculation all over again: