Oracle 中 case的用法

來源:互聯網
上載者:User

CASE運算式可以在SQL中實現if-then-else型的邏輯,而不必使用PL/SQL。CASE的工作方式與DECODE()類似,但應該使用CASE,因為它與ANSI相容。

CASE有兩種運算式:

1. 簡單CASE運算式,使用運算式確定傳回值.

文法:

CASE search_expression

WHEN expression1 THEN result1

WHEN expression2 THEN result2

...

WHEN expressionN THEN resultN

ELSE default_result

END

例:

select product_id,product_type_id,case product_type_idwhen 1 then 'Book'when 2 then 'Video'when 3 then 'DVD'when 4 then 'CD'else 'Magazine'endfrom products

結果:

PRODUCT_ID PRODUCT_TYPE_ID CASEPROD

---------- --------------- --------

         1               1                             Book

         2               1                             Book

         3               2                              Video

         4               2                             Video

         5               2                             Video

         6               2                            Video

         7               3                             DVD

         8               3                             DVD

         9               4                              CD

        10               4                               CD

        11               4                             CD

        12                                            Magazine

12 rows selected.

2. 搜尋CASE運算式,使用條件確定傳回值.

文法:

CASE

WHEN condition1 THEN result1

WHEN condistion2 THEN result2

...

WHEN condistionN THEN resultN

ELSE default_result

END

例:

select product_id,product_type_id,case when product_type_id=1 then 'Book'when product_type_id=2 then 'Video'when product_type_id=3 then 'DVD'when product_type_id=4 then 'CD'else 'Magazine'endfrom products

說明如下: 
1、以CASE開頭,以END結尾 
2、分支中WHEN 後跟條件,THEN為顯示結果 
3、ELSE 為除此之外的預設情況,類似於進階語言程式中switch case的default,可以不加 
4、END 後跟別名 

結果與上相同.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.