case的定义是计算条件列表并返回多个可能结果表达式之一。如果不用case,要达到显示,修改,排序等功能,有时必须要用多条语句来实现,而case则只须用一条语句。
1、在查询显示中使用,这样可以按给定的条件来显示你想显示的内容
select case when au_fname in('johnson','marjorie') then 'johnson' else au_fname end au_fname1,* from authors
2、在修改中使用,可以使要用多条语句才能更改的内容,在一条语句中实现
select * into #authors from authors
update #authors set au_fname=case when au_fname in('johnson','marjorie') then 'johnson' else au_fname end
select *from #authors
drop table #authors
3、在排序中使用,有时更能达到意想不到的效果,如下一条语句的作用单独选作者michael放在第一行,然后把城市akland优先排在第二行之后的行,最后再按作者名排序。
select * from authors order by case au_fname when 'michael' then 0 else 1 end,case city when 'oakland' then 0 else 1 end,au_fname
这种排序在报表的显示及计算中常会用到,如下名:
select * from 报表 order by case 数据类别 when '总计' then 1 else 0,客户,case 数据类别 when '余额' then 0 when '合计' then 2 else 1 end ,日期,case 数据类别 when '现购' then 0 else 1 end
这条语句的作用是把报表的总计记录行放在最后一行,再根据客户的不同分别排序,再对每一个客户记录把余额放在第一行,合计放在最后一行,数据放在中间,数据先按日期排序,相同日期的记录现购记录放在前边,这是光是一个数据类别字段就在排序条件中出现三处,如果不用case则有可能要在记录集再加三个字段,分别计算数据,再来按字段排序,势必要复杂很多,也容易出错