SQL高级查询--decode()函数

decode(value,search_value,result,default_value)对value与search_value进行比较。如果这两个值相等,decode()返回result,否则返回default_value,decode允许

在SQL中执行if-then-else类型的逻辑处理,而不需要使用pl/sql。decode()每个参数都可以是列、字面值、函数和子查询

decode()为oracle所特有的一个函数

 

例1:

select decode(1,1,2,3) from dual;

decode(1,1,2,3)

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

                          2

例2:

select decode(1,2,1,3) from dual;

decode(1,2,1,3)

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

                        3

 

例3:

对more_products表中的available列进行比较。如果available等于Y,返回字符串product is available,否则返回字符串product is not available

select  prd_id,available,decode(available,'Y','product is  available','product is not available') from more_products;

 

prd_id  A  decode(available,'Y'.'pr

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

1         Y    product is  available

2         Y    product is  available

3         N    product is not available

4         N    product is not available

5         Y    product is  available

 

例4:

product_type_id等于1,则返回book

product_type_id等于2,则返回video

product_type_id等于3,则返回dvd

product_type_id等于4,则返回cd

product_type_id等于其他任何值,则返回magazine

 

select product_id,product_type_id,decode(product_type_id,

 1,'book',

 2,'video',

 3,'dvd',

 4,'cd',

 'magazine')

from products;

 

product_id  product_type_id  decode(p

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

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

 

 

 

 

 

你可能感兴趣的:(SQL高级查询)