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

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

准备测试数据:

1
2
3
4
5
6
7
8
9
10
11
12
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后加表达式

  根据表达式结果返回。

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

2. case 后不加表达式

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

1
2
3
4
5
6
7
8
9
10
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

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

1
2
3
4
5
6
7
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 后面,否则会有语法错误。

原文地址:https://www.cnblogs.com/BluceLee/p/8779181.html