Sql 根据字段长度在值中填充空格
我将sql查询设置为:Sql 根据字段长度在值中填充空格,sql,sql-server,tsql,sql-server-2005,Sql,Sql Server,Tsql,Sql Server 2005,我将sql查询设置为: select UJIdentifyer,RecordIdentity,Location,DeptTime,BayNumber,TimingPointIndicatior, FareStageIndicatior from QO where UJIdentifyer='139013' 在这个查询的结果中,每一列的值长度都是固定的 必须有长度为12个字符的位置列 如果是11,那么应该填充一个空格,如果是10,那么应该填充两个空格 为此,我写了: select UJId
select UJIdentifyer,RecordIdentity,Location,DeptTime,BayNumber,TimingPointIndicatior,
FareStageIndicatior
from QO where UJIdentifyer='139013'
在这个查询的结果中,每一列的值长度都是固定的
必须有长度为12个字符的位置
列
如果是11,那么应该填充一个空格,如果是10,那么应该填充两个空格
为此,我写了:
select UJIdentifyer,case when len(RecordIdentity)=11 then RecordIdentity+''else when len(RecordIdentity)=10 then RecordIdentity+' '.... from QO where UJIdentifyer='139013'
像这样,我将不得不写10-12个案件的长度匹配
有什么方法可以避免类似情况的重复吗?试试这个:-
case when datalength(Location ) <12
then Location + replicate (' ' ,12-datalength(Location))
END
使用Datalength
获取包含空格的字符数
Declare @var varchar(12) = 'SQL'
Select datalength(@var) InitialLength,
case when datalength(@var) <12
then @var + replicate (' ' ,12-datalength(@var))
END as PaddingExtraSpaces,
Datalength(case when datalength(@var) <12
then @var + replicate (' ' ,12-datalength(@var))
END ) FinalLength
IntialLength PaddingExtraSpaces FinalLength
2 SQL 12