SQL Server中使用判断语句(IF ELSE/CASE WHEN )案例

sql server判断语句(if else/case when )

执行顺序是 – 从上至下 – 从左至右 –,所当上一个条件满足时(无论下面条件是否满足),执行上个条件,当第一个条件不满足,第二个条件满足时,执行第个二条件

1、if else

不能用在select中,只能是块,比如:

if …

begin

…(代码块)

end

else (注意这里没有else if,要实现只能在下面的块中用if判断)

begin

…(代码块)

end

列:

declare @num int –定义变量

set @num=1 –赋值变量

if(@num>10)

begin

select * from 表1

end

else

begin

if(@num<0)

select top(20) * from 表2

else

print @num

end

2、case when then else end

可以在select中使用,但是要包括end结尾

case …

when … (条件/代码块) then …(返回值/case when then else end)

else …(可省略)

end

列:

declare @num int –定义变量

set @num=111 –赋值变量

select @num,

case

when @num<=100 then case

when @num>=80 then ‘a’

when @num>=60 then ‘b’

else ‘c’ end

when @num>=200 then ‘优秀’

else ‘haha’

end

到此这篇关于sql server中使用判断语句(if else/case when )案例的文章就介绍到这了,更多相关sql server使用判断语句内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐