How to convert int to char with leading zeros?

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

    I was wondering, would this be on any use to you?

    declare @val int,@len=800
    select replace(str(@val,@len),' ','0')
    
    0 讨论(0)
  • 2020-12-12 19:20

    I like to use

    DECLARE @Length int
    DECLARE @Number int
    SET @Length = 9
    SET @Number = 4
    
    select right( POWER(10, @Length) + @Number, @Length)
    

    this gives me

    000000004
    
    0 讨论(0)
  • 2020-12-12 19:20

    One line solution (per se) for SQL Server 2008 or above:

    DECLARE @DesiredLenght INT = 20;
    SELECT 
        CONCAT(
            REPLICATE(
                '0',
                (@DesiredLenght-LEN([Column])) * (1+SIGN(@DesiredLenght-LEN([Column])) / 2) ),
            [Column])
    FROM Table;
    

    Multiplication by SIGN expression is equivalent to MAX(0, @DesiredLenght-LEN([Column])). The problem is that MAX() accepts only one argument...

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

    In my case I wanted my field to have leading 0's in 10 character field (NVARCHAR(10)). The source file does not have the leading 0's needed to then join to in another table. Did this simply due to being on SQL Server 2008R2:

    Set Field = right(('0000000000' + [Field]),10) (Can't use Format() as this is pre SQL2012)

    Performed this against the existing data. So this way 1 or 987654321 will still fill all 10 spaces with leading 0's.

    As the new data is being imported & then dumped to the table through an Access database, I am able to use Format([Field],"0000000000") when appending from Access to the SQL server table for any new records.

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

    You can also use FORMAT() function introduced in SQL Server 2012. http://technet.microsoft.com/library/hh213505.aspx

    DECLARE @number1 INT, @number2 INT
    
    SET @number1 = 1
    SET @number2 = 867
    
    SELECT FORMAT(@number1, 'd10')
    SELECT FORMAT(@number2, 'd10')
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题