How to convert int to char with leading zeros?

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

    Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.

    Example:

    SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)
    

    Result: '000867'

    0 讨论(0)
  • 2020-12-12 19:28

    This work for me in MYSQL:

    FUNCTION leadingZero(format VARCHAR(255), num VARCHAR(255))
      RETURNS varchar(255) CHARSET utf8
    BEGIN
      return CONCAT(SUBSTRING(format,1,LENGTH(format)-LENGTH(num)),num);
    END
    

    For example:

    leadingZero('000',999); returns '999'
    leadingZero('0000',999); returns '0999'
    leadingZero('xxxx',999); returns 'x999'
    

    Hope this will help. Best regards

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-12 19:30

    Works in SQLServer

    declare @myNumber int = 123
    declare @leadingChar varchar(1) = '0'
    declare @numberOfLeadingChars int = 5
    
    select right(REPLICATE ( @leadingChar , @numberOfLeadingChars ) + cast(@myNumber as varchar(max)), @numberOfLeadingChars)
    

    Enjoy

    0 讨论(0)
  • 2020-12-12 19:31

    Had same issue, this is how I resolved... Simple and elegant. The "4" is how long the string should be, no matter what length of integer is passed it will pad with zero's up to "4".

    STUFF(SomeVariableOrField,1,0,REPLICATE('0',4 - LEN(SomeVariableOrField)))
    
    0 讨论(0)
提交回复
热议问题