Can I use a column calculated in a SQL Server view later on in that same view?
Let’s say I have the following view:
Select
t1.StartMile, t2.EndMile, t2.EndMile- t1.StartMile as TotMile
from
TableStarts as t1
inner join
TableEnds as t2 on t1.Id = t2.Id
Is there a way to edit the view to do the following
Select
t1.StartMile, t2.EndMile, t2.EndMile - t1.StartMile as TotMile,
TotMile + 30 as EvenMoreMiles
I tried this and got error:
Invalid column name ‘TotMile’
Please don’t tell me to use t2.EndMile - t1.StartMile + 30 as EvenMoreMiles. TotMiles is a long case statement in my actual code.
I rather not have to create an intermediate view.
I am using SQL Server 2005.
ADDED LATER
Thanks for all the answers. I will upvote all.
The answers raise the following new question:
Given that there are thousands of rows, and TotMiles looks like the following, which of the answers given would be the most efficient? Or would it be most efficient to create an intermediary view?
CASE WHEN t .TaskType = 1 and t .StartTime < '1/1/2012'
THEN (tv.EndMile - tv.StartMile )
WHEN NOT (t .Location1_PKey = c.pkey OR t .Location2_PKey = c.pkey)
then (tv.EndMile - tv.StartMile )
WHEN (tv.EndMile - tv.StartMile ) < 31 Then 0
ELSE (tv.EndMile - tv.StartMile - 30 )
END AS MilesAdjusted2012,
You can also use
CROSS APPLYwhich can be more concise, particularly if you are building up chains of aliases that reference preceding ones.