# SQL msSQL Case When Then 函式 ---- ###### tags: `SQL` [CASE 關鍵字 (SQL CASE Keyword)](https://www.fooish.com/sql/case.html) 再使用分頁時有一串sql語法是這樣寫的 中間的 `case then`因為不是很懂 所以花了點時間 ```sql= SELECT * FROM (SELECT ROW_NUMBER() OVER ( ORDER BY (case id when '1' then 0 else 1 end) ASC, id DESC ) AS row_id, * FROM [admin_basic] ) AS atabe WHERE charindex('o', admin_acc) > 0 ORDER BY row_id ``` 輸出結果 [](https://i.imgur.com/rfajLGF.png) ![](https://raw.githubusercontent.com/bestRDJ333/noteImg/main/img/56.png) 原本結果 [](https://i.imgur.com/KcHoYOE.png) ![](https://raw.githubusercontent.com/bestRDJ333/noteImg/main/img/57.png) ## case then else 就是類似於 程式中的 `if else`概念 將中間的`case then else`單獨看 意思是 case 是要比較的陳述句 或是 欄位名稱 當 case 比較結果符合下面的 when 的話回傳 then 的值 如果不符合的話 就一律回傳 else的值 ```sql= SELECT case id when '1' then 0 else 1 end Answer ,* FROM [admin_basic] ORDER BY Answer; ``` ![](https://i.imgur.com/7INAc9h.png) ---- ---- ``` CASE WHEN condition THEN result [WHEN···] [ELSE result] END; ``` ``` CASE expression WHEN value THEN result [WHEN···] [ELSE result] END; ``` ----- --- ### 網站範例 ``` select Name, case Answer when 1 then '喜歡' when 2 then '不喜歡' when 3 then '還OK' END FROM questionnaire; ``` ---- [](https://i.imgur.com/x0dx24G.png) ![](https://raw.githubusercontent.com/bestRDJ333/noteImg/main/img/59.png) ----- ----