CASE陳述句是SQL-92內標準SQL。SQL大師權威Joe Celko認為CASE陳述式或許是SQL-92最為有用的功能之一。本文主要講解CASE語法。當熟練後,不僅能讓SQL語法更加靈活,也能減少許多沉長的語句。
CASE可分為單純CASE陳述式(simple case)
CASE
WHEN condition THEN result
[WHEN···]
[ELSE result]
END;
和搜尋CASE陳述式(searched case)
CASE expression
WHEN value THEN result
[WHEN···]
[ELSE result]
END;
注意
- 各分條件傳回的資料類型必須一致
- 記得加上END
- 一定要撰寫ELSE陳述句
我們看看如何使用case來減少SQL語法撰寫。
–條件1
Update Employee
SET salary = salary * 0.9
WHERE salary >= 30000
–條件2
Update Employee
SET salary = salary * 1.2
WHERE salary >= 25000 AND salary < 28000
現在我們改用CASE
UPDATE Employee
SET salary = CASE WHEN salary >= 30000
THEN salary * 0.9
WHEN salary >= 25000 AND salary < 28000
THEN salary * 1.2
ELSE salary END;
上例顯示正確使用case只須執行一次SQL有助於提升效能
再提出兩個例子
例子1
表:sq1Q1

試者從這張資料表取得x與y的最大值
SQL語法為:

結果為

例子2
表: PopTbl2

請製作總結果以及欄位的交叉分析表
SQL語法為:


熟練CASE語句是DBA人員必備的條件,期望本文能提供些幫助。