2014-01-28 59 views
0

當我嘗試執行上SSMS 2012 Express中的以下腳本:SQL Server 2012的SSMS的智能感知「無效列名」在WHERE子句

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 

「智能感知」說:「無效的列名」指的是「ItemTotal 「僅在WHERE子句中。如果我註釋掉或刪除WHERE子句,即使在ORDER BY子句中也調用了「ItemTotal」,它仍可以很好地工作。

請幫忙。

很多謝謝。

+0

在Where子句你算算' ItemTotal'。 – Prashant16

+0

檢查我的答案..! –

回答

2

這是因爲WHEREORDER BY在執行過程中,在兩個不同的時間進行評估:

  • WHERE:這是第一次評估,啓動建設的「表」,你選擇會顯示
  • 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 ! 
+0

我認爲這可能是這種情況,但我只是認爲SSMS 2012會更好地挑選它。感謝您爲我清理,但!非常感激! – user2986163

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

希望這有助於

編碼快樂