日期:2014-05-19  浏览次数:20896 次

如何判断字段是否达到指定位数,如果不够用空格补齐
例如:   TABLE表有字段A,B,C

现在想取得表里字段A+B+C的数据,如果A字段记录不够五位就要加空格补齐,B和C同样,如:   A             B           C                   A+B+C
            12345   67890     56789       123456789056789
            1234     678         56789       1234   678     56789
            ...       ....       ....         ...............

------解决方案--------------------
select left(A+ ' ',5)+left(B+ ' ',5)+left(C+ ' ',5) from tb
------解决方案--------------------
alter table tb
alter column b char(5)
------解决方案--------------------
select a+b+c as 'add ' from(
select a =case len(a)
when '5 ' then a
else a+space(5-len(a))
end,
b=case len(b)
when '5 ' then b
else b+space(5-len(b))
end,
c=case len(c)
when '5 ' then c
else c+space(5-len(c))
end
from xx) d
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb
(
A varchar(5),
B varchar(5),
C varchar(5)
)

insert into tb(A,B,C) values( '12345 ', '67890 ', '56789 ')
insert into tb(A,B,C) values( '1234 ' , '678 ' , '56789 ')

select A,B,C,left(A + ' ' , 5) + left(B + ' ' , 5) + left(C + ' ' , 5) as 'A+B+C ' from tb

drop table tb

/*result
A B C A+B+C
----- ----- ----- ------------------------------
12345 67890 56789 123456789056789
1234 678 56789 1234 678 56789

(所影响的行数为 2 行)
*/
------解决方案--------------------
学了一招啊
select left(A + ' ' , 5) from tb
现给后面都加5个空格,然后再从前面取5个,大家脑子怎么都这么好使?
------解决方案--------------------
觉得改char(5)最好
------解决方案--------------------
改char(5)太现实了,没有考虑楼主是否还有其他需求.
------解决方案--------------------
mark