有时从数据库中检索出来的数据,需要进行格式化,例如性别在数据库中存储 1 表示男性, 0 表示女性,在显示时要将 1 替换成男, 0 替换成女,这里方法是多样的,可以在服务器端进行,也可以在客户端进行。
在服务器端利用 sql 查询语句,下面有两种方法。
方法一:利用 case
declare
@tb
table
(name
char
(
5
),sex
int
)
insert
@tb
select
'
Andy
'
,
1
union
all
select
'
Jim
'
,
1
union
all
select
'
Lily
'
,
0
union
all
select
'
Linda
'
,
null
![](/Images/OutliningIndicators/None.gif)
select
name,
sex
=
CASE
WHEN
sex
=
1
THEN
'
男
'
when
sex
=
0
then
'
女
'
end
from
@tb
结果:
name sex
----- ----
Andy 男
Jim 男
Lily 女
Linda NULL
方法二 利用 join
declare
@tb
table
(name
char
(
5
),sex
int
)
insert
@tb
select
'
Andy
'
,
1
union
all
select
'
Jim
'
,
1
union
all
select
'
Lily
'
,
0
union
all
select
'
Linda
'
,
null
![](/Images/OutliningIndicators/None.gif)
select
t.name,t.sex,s.SexTitle
from
@tb
t
left
join
(
select
1
as
SexID,
'
男
'
as
SexTitle
union
all
select
0
,
'
女
'
) s
on
t.sex
=
s.SexID
结果:
name sex SexTitle
----- ----------- --------
Andy 1 男
Jim 1 男
Lily 0 女
Linda NULL NULL