How to convert int to char with leading zeros?

后端 未结 17 833
一生所求
一生所求 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:26

    Use REPLICATE so you don't have to hard code all the leading zeros:

    DECLARE @InputStr int
           ,@Size     int
    SELECT @InputStr=123
          ,@Size=10
    
    PRINT REPLICATE('0',@Size-LEN(RTRIM(CONVERT(varchar(8000),@InputStr)))) + CONVERT(varchar(8000),@InputStr)
    

    OUTPUT:

    0000000123
    

提交回复
热议问题