How to use alias column name in where clause in SQL Server

后端 未结 5 1828
时光说笑
时光说笑 2020-11-27 06:49

When I tried to perform the below code in SQL Server 2005 I am getting the error

Invalid column name DistanceFromAddress

Code:<

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 06:53

    The WHERE clause is processed before the SELECT clause(*), and so the aliases aren't available. Move to using a subquery or CTE - here's a CTE:

    ; with Distances as (
        select SQRT(POWER(cast(Program_Latitude as float) - cast('41.5126237' as float), 2) +   
     POWER(cast(Program_Longitude as float) - cast('-81.6516411' as float), 2)) * 62.1371192 
     AS DistanceFromAddress
        from tblProgram
    )
    select * from Distances where DistanceFromAddress < 2
    

    (*) - well, systems are free to re-order operations as they see fit, so long as the result is "as if" the SQL statement was processed in a certain logical order. Of course, where this all goes wrong with SQL Server is where it produces errors because of conversion issues in the SELECT clause for rows/values that should be eliminated by the WHERE clause.

提交回复
热议问题