case when用法:
case when 条件表达式1 then 返回值1 when 条件表达式2 then 返回值2 else 缺省值 end)
例如:
/*用法1*/
select case when sex = 0 then '男' else '女' end as 性别 from table_name;
/*用法2*/
select case when sex = 0 then '男'
when sex = 1 then '女' else '' end as 性别 from table_name;
decode用法:
decode(条件,值1,返回值1,值2,返回值2,…值n,返回值n,缺省值)
例如:
select decode(sex,0,'男',1,'女','') as 性别 from table_name
区别:
- decode只能用在oracle、达梦数据库有一定局限性,而case when比较通用;
- decode表达式只能是等式判断,而case when可以用于=,>=,<,<=,<>,is null,is not null 等的判断;
- decode格式使用起来比较简洁,case when格式复杂但更为灵活;