请教一条SQL语句,获得想要的字符位数
表格中有一个数值是1-100的任意数,如果是1,如何使输出为001;如果55,如何输出为055?
[解决办法]
declare @a int
set @a=1
select stuff(@a+1000,1,1,'')
declare @tb table(colName int)
insert into @tb
select 1 union all
select 55 union all
select 76 union all
select 2 union all
select 100
select right(replicate('0',2)+CONVERT(varchar(3),colName),3) as NewCol from @tb
--结果
NewCol
------
001
055
076
002
100
(5 行受影响)
WITH tt(num)
AS
(
SELECT '100'
UNION ALL
SELECT '50'
UNION ALL
SELECT '4'
UNION ALL
SELECT '78'
)
--SELECT STUFF(num+1000,1,1,'') AS NewNum
--FROM tt --数值
SELECT CASE WHEN LEN(num)=1 THEN '00'+num
WHEN LEN(num)=2 THEN '0'+num
ELSE num
END AS NewNum
FROM tt --字符
create table lm(x int)
insert into lm(x)
select 1 union all
select 55 union all
select 100 union all
select 40 union all
select 5
select replicate('0',3-len(x))+rtrim(x) 'x' from lm
/*
x
------------------------
001
055
100
040
005
(5 row(s) affected)
*/
WITH tt(num)
AS
(
SELECT '100'
UNION ALL
SELECT '50'
UNION ALL
SELECT '4'
UNION ALL
SELECT '78'
)
--SELECT STUFF(num+1000,1,1,'') AS NewNum
--FROM tt --数值
SELECT CASE WHEN LEN(num)=1 THEN '00'+num
WHEN LEN(num)=2 THEN '0'+num
ELSE num
END AS NewNum
FROM tt --字符
WITH tt(num)
AS
(
SELECT '100'
UNION ALL
SELECT '50'
UNION ALL
SELECT '4'
UNION ALL
SELECT '78'
)
SELECT num=RIGHT('000' + LTRIM(num), 3) FROM tt
/*
num
100
050
004
078
*/