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
注:其中[]内都是可选的。
准备测试数据:
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 1 then N '组1' when 2 then N '组2' when 3 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 后面,否则会有语法错误。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?