sql 数据检索后的替换格式化

有时从数据库中检索出来的数据,需要进行格式化,例如性别在数据库中存储 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

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

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   

posted @ 2007-10-10 09:14  Felix Liang  阅读(284)  评论(0)    收藏  举报