特殊整数转换

时间:2011-09-16 11:50:18

标签: sql sql-server stored-procedures

是否可以转换4位varchar中的整数。例如,我得到整数1,我得到varchar'0001',对于整数550,我得到varchar'0550'。

由于

4 个答案:

答案 0 :(得分:3)

还是这个?

right('000'+ convert(varchar,MyNum),4)

我只是对各种方法做了一些粗略的时间,这个解决方案似乎比其他方法快一点。这让我感到惊讶......

DECLARE @loop INT;
DECLARE @MyNum INT;
DECLARE @Upper INT;
DECLARE @Lower INT;
DECLARE @result VARCHAR;
DECLARE @start DATETIME;

SET @Lower = 1;
SET @Upper = 9999;  
SET @loop = 10000;

SET @start = GETDATE();

WHILE @loop > 0 BEGIN
  SELECT @MyNum = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0);
  SET @loop = @loop -1;
  SET @result = right('000'+ convert(varchar,@MyNum),4);
  -- SET @result = right(10000 + @MyNum, 4);
  -- SET @result = right(convert(float, @MyNum) / 10000, 4);
  -- SET @result = stuff('0000', 1 + 4 - len(@MyNum), len(@MyNum), @MyNum);
  -- SET @result = replace(str(@MyNum, 4), ' ', '0');   
END;

SELECT GETDATE() - @start;

答案 1 :(得分:1)

试试这个:

SELECT REPLACE(STR(550, 4), ' ', '0')

<!/ P>

答案 2 :(得分:1)

declare @Num int 
set @Num = 1

select right(10000+@Num, 4)

答案 3 :(得分:0)

单向(如果len输入&gt; 4则为NULL);

;with t(f) as (
    select 1 union select 11 union select 111 union select 1111
)

select
    f,
    stuff('0000', 1 + 4 - len(f), len(f), f)
from t

>>
f      (No column name)
1      0001
11     0011
11     0111
1111   1111