Home > Database > Mysql Tutorial > Oracle case when用法

Oracle case when用法

WBOY
Release: 2016-06-07 17:57:59
Original
1280 people have browsed it

CASE表达式可以在SQL中实现if-then-else型的逻辑,而不必使用PL/SQL。CASE的工作方式与DECODE()类似,但应该使用CASE,因为它与ANSI兼容。 注意点: 1、以CASE开头,以END结尾 2、分支中WHEN后跟条件,THEN为显示结果 3、ELSE为除此之外的默认情况,类似于高级

CASE表达式可以在SQL中实现if-then-else型的逻辑,而不必使用PL/SQL。CASE的工作方式与DECODE()类似,但应该使用CASE,因为它与ANSI兼容。
注意点:

  1、以CASE开头,以END结尾

  2、分支中WHEN后跟条件,THEN为显示结果

  3、ELSE为除此之外的默认情况,类似于高级语言程序中switch case的default,可以不加

  4、END后跟别名

  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_id

  when 1 then 'Book'

  when 2 then 'Video'

  when 3 then 'DVD'

  when 4 then 'CD'

  else 'Magazine'

  end

  from 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'

  end

  from products

  结果与上相同.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template