2012-02-10 39 views
0

是否可以訪問在公共表表達式的查詢中定義的臨時列?說我有T-SQL:訪問公共表表達式中的臨時列

select * from myTable 

;with cte as 
(
    select 
     *, Salary * 4 as FourTimesSalary 
    from 
     Employees 
    where 
     Name = @name 
     and ID >= 100 
) 

有沒有像這樣CTE查詢時使用的臨時列FourTimesSalary的方法嗎?

select top 2 * 
from cte 
order by FourTimesSalary, Name 

TIA。

回答

1

是的,你可以做到這一點。例如:

with temp as 
(
    select 1 as id, 2*4 as val 
    UNION 
    select 2 as id, 3*4 as val 
) 
SELECT * FROM temp ORDER BY VAL desc 

你的榜樣看起來不錯,沒當你嘗試過什麼,你得到一個錯誤?

+0

是的,錯誤表明我沒有列名FourTimesSalary定義。原來在我的查詢語句中是一個問題。 – 2012-02-10 22:18:33