0

首先,我将表中的值转换为整数

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 是可以接受的

我怎样才能做到这一点?

4

3 回答 3

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
于 2012-07-20T19:43:20.450 回答
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 
于 2012-07-20T20:02:14.787 回答
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 来完成。

于 2012-07-20T20:11:26.260 回答