How to convert int to char with leading zeros?

后端 未结 17 870
一生所求
一生所求 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条回答
  •  旧时难觅i
    2020-12-12 19:12

    Not to High-Jack this question but the note needs to be made that you need to use (N)VARCHAR instead of (N)CHAR data-type.

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

    Above segment, will not produce the correct response from SQL 2005

    RIGHT('000' + CAST(@number1 AS NVARCHAR(3)), 3 )
    

    Above segment, will produce the desired response from SQL 2005

    The the varchar will provide you with the desired prefix length on the fly. Where as the fixed length data type will require length designation and adjustments.

提交回复
热议问题