How to convert int to char with leading zeros?

后端 未结 17 824
一生所求
一生所求 2020-12-12 18:55

I need to convert int datafield to nvarchar with leading zeros

example:

1 convert to \'001\'

867 convert to \'000867\', etc.

thx.


17条回答
  •  执笔经年
    2020-12-12 19:29

    DECLARE @number1 INT, @number2 INT
    
    SET @number1 = 1
    
    SET @number2 = 867
    

    -- Without the 'RTRIM', the value returned is 3__ !!!

    SELECT RIGHT('000' + RTRIM(CAST(@number1 AS NCHAR(3)), 3 )) AS NUMBER_CONVERTED
    

    -- Without the 'RTRIM', the value returned is 867___ !!!

    SELECT RIGHT('000000' + RTRIM(CAST(@number2 AS NCHAR(6)), 6 )) AS NUMBER_CONVERTED
    

提交回复
热议问题