SQL Server 2012 SSMS Intellisense在WHERE子句中说“无效的列名称”

时间:2014-01-28 05:34:27

标签: sql sql-server

当我尝试在SSMS 2012 Express上执行以下脚本时:

SELECT ItemID, ItemPrice, DiscountAmount, Quantity, 
    ItemPrice * Quantity AS PriceTotal, 
    DiscountAmount * Quantity AS DiscountTotal, 
    Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
FROM OrderItems
WHERE ItemTotal > 500
ORDER BY ItemTotal DESC

“Intellisense”在WHERE子句中引用“ItemTotal”和“仅在WHERE子句中”表示“无效列名称”。如果我注释掉或删除WHERE子句,即使在ORDER BY子句中也调用了“ItemTotal”,它也能正常工作。

请帮忙。

非常感谢。

2 个答案:

答案 0 :(得分:2)

这是因为WHEREORDER BY在执行期间的两个不同时间进行评估:

  • WHERE :首先评估此项,然后开始构建 SELECT 将显示的“表格”
  • ORDER BY :计算此“表格”后对此进行评估,以便按照您提到的列开始排序

别名(即 AS 子句后面的名称)是对此“表格”列的某种“重命名”,它将与 SELECT 一起显示。这意味着在计算 WHERE 子句时它们尚不存在。

ORDER BY 在构建table后发生,因此系统现在知道别名引用的列。

要做你想做的事,你必须写:

SELECT ItemID, ItemPrice, DiscountAmount, Quantity, 
       ItemPrice * Quantity AS PriceTotal, 
       DiscountAmount * Quantity AS DiscountTotal, 
       Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
FROM OrderItems
WHERE Quantity * (ItemPrice - DiscountAmount) > 500 --here SQL doesn't know what "ItemTotal" is...
ORDER BY ItemTotal DESC -- but at this stage it does understand !

答案 1 :(得分:0)

Select * from 
            ( SELECT ItemID, 
                     ItemPrice,
                     DiscountAmount,
                     Quantity, 
                     ItemPrice * Quantity AS PriceTotal, 
                     DiscountAmount * Quantity AS DiscountTotal, 
                     Quantity * (ItemPrice - DiscountAmount) AS ItemTotal
              FROM OrderItems
             ) as t
         WHERE ItemTotal > 500 
         ORDER BY ItemTotal DESC 

Sample Working Sql Fiddle

希望这有帮助

快乐编码