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 后面,否則會有語法錯誤。