bAN
bAN

Reputation: 13835

Special integer conversion

Is it possible to convert an integer in 4 position varchar.. Example I have the integer 1 and I get varchar '0001', for integer 550 I get varchar '0550' .

Thanks

Upvotes: 2

Views: 150

Answers (4)

Hugh Jones
Hugh Jones

Reputation: 2694

or this ?

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

I just did some rough timings on the various methods and this solution seemed to be a little quicker than the others. That surprised me ...

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;

Upvotes: 3

Mikael Eriksson
Mikael Eriksson

Reputation: 138980

declare @Num int 
set @Num = 1

select right(10000+@Num, 4)

Upvotes: 1

Alex K.
Alex K.

Reputation: 175846

Onw way (NULL if len input > 4);

;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

Upvotes: 0

Arnaud F.
Arnaud F.

Reputation: 8452

Try this :

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

!

Upvotes: 1

Related Questions