Search code examples
sql-servercastingvarchar

SQL Server casting a varchar to int


I have the following scenario:

DECLARE @m VARCHAR(50) = '000000001'

WHILE (@m <= 10)
BEGIN
        PRINT @m
        -- Increment the iterator
        SET @m = @m  + 1
END

When I run the above code I get:

000000001
2
3
4
5
6
7
8
9
10

The problem is, I need the result to be as following:

000000001
000000002
000000003
000000004
000000005
000000006
000000007
000000008
000000009
000000010

I want the eight 0's to show up before the number when it is increasing, and it will be seven 0's when the number reaches 10. I tried the following but it didn't work, there will be as you guessed eight 0's before the 10.

DECLARE @m VARCHAR(50) = '1'

WHILE (@m <= 10)
BEGIN
        PRINT '00000000' +@m
        -- Increment the iterator
        SET @m = @m  + 1
END

Basically I want to keep only 9 digits, this might sound stupid but what can I say (My boss wants it like that).


Solution

  • If you really must:

    DECLARE @i int; Set @i = 1;
    WHILE @i <= 10
    BEGIN
        PRINT RIGHT('00000000' + cast(@m as char(9)), 9);
        SET @i = @i + 1;
    END 
    

    But please don't. Data should be stored raw, and only formatted at display time, preferably by the client application.