sql case 用法总结

  快下班了,抽点时间总结一下sql 的 case 用法。

  sql 里的case的作用: 用于计算条件列表的表达式,并返回可能的结果之一。sql 的case 类型于编程语言里的 if-esle if-else 或者 switch,但它不用于控制sql程序的执行流程,而是作为的逻辑使用。

  语法:

  case [input_expression]

      when when_expression then result_expression

  [...n]

  [else else_result_expression]

  end

  注:其中[]内都是可选的。

准备测试数据:

declare @stuinfo table
(id int,
 sname nvarchar(20),
 gender varchar(1),
 sgroup int)

insert into @stuinfo
select 1,'张三','m',1 union all
select 2,'李四','f',1 union all
select 3,'王五','f',2 union all
select 4,'赵六','m',3 union all
select 5,'黄七','m',3 

1. case后加表达式

  根据表达式结果返回。

select *,
	   case sgroup
	   when 1 then N'组1'
	   when 2 then N'组2'
	   when 3 then N'组3' 
	   else N'未知' end groupname
  from @stuinfo

2. case 后不加表达式

  不加表达式,则根据when的条件返回。

select *,
	   case 
	   when sgroup = 1 and gender = 'm' then N'第一组男生'
	   when sgroup = 1 and gender = 'f' then N'第一组女生'
	   when sgroup = 2 and gender = 'm' then N'第二组男生'
	   when sgroup = 2 and gender = 'f' then N'第二组女生'
	   when sgroup = 3 and gender = 'm' then N'第三组男生'
	   when sgroup = 3 and gender = 'f' then N'第三组女生'
	   else N'未知' end comment
  from @stuinfo

3. 用于 order by

  如果存储过程需要支持多种排序,可以传递一个参数变量,然后根据该变量判断即可。

declare @orderby int
set @orderby = 1

select * from @stuinfo
order by
	case when @orderby = 1 then id end desc,
	case when @orderby = 2 then id end

  这里要用多个case,因为desc需要放在end 后面,否则会有语法错误。

posted @ 2015-09-18 17:57  我是攻城狮  阅读(30734)  评论(1编辑  收藏  举报