-- 錯誤:'至少一個參數沒有被指定值'
SELECT W.ID, W.Weather, greenColor,
(SELECT redColor+greenColor+blueColor FROM Weather N WHERE N.ID = W.ID) AS AllValue
FROM Weather W
WHERE AllValue > 0 -- 無效:WHERE 階段尚未計算 SELECT 列別名
ORDER BY ID;
原因:SQL 執行順序 FROM → WHERE → SELECT,WHERE 看不見 SELECT 的別名。
SELECT W.ID, W.Weather, greenColor,
(SELECT redColor+greenColor+blueColor FROM Weather N WHERE N.ID = W.ID) AS AllValue
FROM Weather W
WHERE (SELECT redColor+greenColor+blueColor FROM Weather N WHERE N.ID = W.ID) > 0
ORDER BY ID;
SELECT W.ID, W.Weather, W.greenColor, CA.AllValue
FROM Weather W
CROSS APPLY (
SELECT redColor+greenColor+blueColor AS AllValue
FROM Weather N WHERE N.ID = W.ID
) CA
WHERE CA.AllValue > 0
ORDER BY W.ID;
WITH Calculated AS (
SELECT ID, Weather, greenColor,
redColor+greenColor+blueColor AS AllValue
FROM Weather
)
SELECT ID, Weather, greenColor, AllValue
FROM Calculated
WHERE AllValue > 0
ORDER BY ID;
SELECT ID, Weather, greenColor,
redColor+greenColor+blueColor AS AllValue
FROM Weather
WHERE redColor+greenColor+blueColor > 0
ORDER BY ID;
| 寫法 | 適用場景 | 效能 | 可讀性 |
|---|---|---|---|
| 直接計算 | 單表、簡單運算 | ★★★★★ | ★★★★★ |
| CTE | 複雜計算、多次引用、跨表 | ★★★★☆ | ★★★★★ |
| CROSS APPLY | 需逐列呼叫函數/複雜邏輯 | ★★★★☆ | ★★★★☆ |
| 重複子查詢 | 快速原型、一次性查詢 | ★★☆☆☆ | ★★★☆☆ |