首先,我将表中的值转换为整数,如
cast(convert(int, isnull(b.temp,0)) as varchar(500))
然后我想输出如下所示的值,例如
1 as 001
12 as 012
123 as 123
-1 as -001
-15 as -015
-234 as -234
如果整数值的长度大于3,则不显示任何值或将其删除。 如果整数具有减号( - ),那么它不是长度的一部分 所以-001被视为长度3
所以001和-001是可接受的长度3
我该怎么做?
答案 0 :(得分:2)
看起来你正试图在一个范围内填0。这是我这样做的一种方式:
select (case when val between 0 and 999
then right('000'+cast(<col> as varchar(100)), 3)
when val between -999 and 0
then '-'+right('000'+cast(abs(<col>) as varchar(100)), 3)
else ''
end)
from t
答案 1 :(得分:0)
以下解决方案有效。感谢
declare @num1 as varchar(50)
set @num1 = '1'
select (case
when @num1 between 0 and 999 then right('000'+cast(@num1 as varchar(100)), 3)
when @num1 between -999 and 0 then '-'+right('000'+cast(abs(@num1) as varchar(100)), 3)
else ''
end) as t
答案 2 :(得分:0)
确实没有有效的方法可以做到这一点,但我知道有些情况需要这样做。我可能会用这样的东西变成一个函数。
DECLARE @myInt as INT
SET @myInt = -9
DECLARE @padding AS VARCHAR(1)
SET @padding = '0'
DECLARE @length AS INT
SET @length = 3 - LEN(ABS(@myInt))
DECLARE @result AS VARCHAR(5)
SET @result = REPLICATE(@padding, @length) + cast(ABS(@myInt) as VARCHAR(3))
IF @myInt < 0
SET @result = '-' + @result
SELECT @result
这真的应该在代码而不是sql中完成。