我需要从数据库表中获取固定长度值。以下是查询
select cast(TrackID as char(4)) as TrackID ,
cast(Tracknumber as char(5)) as Tracknumber
from Tracking
当列值为null或为空时,我希望显示相同数量的零。
TrackID -- TrackNumber 2121 -- 34343 3423 -- 00000
答案 0 :(得分:5)
您可以使用coalesce()
/ case
:
select cast(TrackID as char(4)) as TrackID ,
coalesce(cast(Tracknumber as char(5)), '00000') as Tracknumber
from Tracking;
需要强制转换,因此结果是字符串,而不是数字。
如果没有NULL
,“数字”不能为“空”。如果该值实际上是一个字符串,那么您需要稍微复杂的逻辑:
select cast(TrackID as char(4)) as TrackID ,
(case when Tracknumber is null or Tracknumber = ''
then '00000'
else cast(Tracknumber as char(5))
end) as Tracknumber
from Tracking;
答案 1 :(得分:0)
就这样做......
select cast(TrackID as char(4)) as TrackID ,
isnull(nullif(cast(Tracknumber as char(5)),''),'00000') as Tracknumber
from Tracking