sqlcase用法总结

sqlcase用法总结

2023年6月27日发(作者:)

sqlcase⽤法总结  快下班了,抽点时间总结⼀下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 @stuinfoselect 1,'张三','m',1 union allselect 2,'李四','f',1 union allselect 3,'王五','f',2 union allselect 4,'赵六','m',3 union allselect 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 @stuinfo2. 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 @stuinfo3. ⽤于 order by  如果存储过程需要⽀持多种排序,可以传递⼀个参数变量,然后根据该变量判断即可。declare @orderby intset @orderby = 1select * from @stuinfoorder by case when @orderby = 1 then id end desc, case when @orderby = 2 then id end  这⾥要⽤多个case,因为desc需要放在end 后⾯,否则会有语法错误。

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687816872a47685.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信