How to convert int to char with leading zeros?

Sql ServerStored Procedures

Sql Server Problem Overview


I need to convert int datafield to nvarchar with leading zeros

example:

1 convert to '001'

867 convert to '000867', etc.

thx.


This is my response 4 Hours later ...

I tested this T-SQL Script and work fine for me !

DECLARE @number1 INT, @number2 INT

SET @number1 = 1

SET @number2 = 867

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

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

I created this user function

T-SQL Code :

CREATE FUNCTION CIntToChar(@intVal BIGINT, @intLen Int) RETURNS nvarchar(20)
AS
BEGIN

    -- BIGINT = 2^63-1 (9,223,372,036,854,775,807) Max size number

    -- @intlen contains the string size to return
    IF @intlen > 20
       SET @intlen = 20
	
    RETURN REPLICATE('0',@intLen-LEN(RTRIM(CONVERT(nvarchar(20),@intVal)))) 
        + CONVERT(nvarchar(20),@intVal)

END

Example :

SELECT dbo.CIntToChar( 867, 6 ) AS COD_ID

OUTPUT

000867

Sql Server Solutions


Solution 1 - Sql Server

Try this: select right('00000' + cast(Your_Field as varchar(5)), 5)

It will get the result in 5 digits, ex: 00001,...., 01234

Solution 2 - Sql Server

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')

Solution 3 - Sql Server

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

Solution 4 - Sql Server

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.

Solution 5 - Sql Server

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

Solution 6 - Sql Server

Data type "int" cannot be more than 10 digits, additionally the "Len()" function works on ints, so there's no need to convert the int to a string before calling the len() function.

Lastly, you are not taking into account the case where the size of your int > the total number of digits you want it padded to (@intLen).

Therefore, a more concise / correct solution is:

CREATE FUNCTION rf_f_CIntToChar(@intVal Int, @intLen Int) RETURNS nvarchar(10)
AS
BEGIN
    IF @intlen > 20 SET @intlen = 20
    IF @intlen < LEN(@intVal) RETURN RIGHT(CONVERT(nvarchar(10), @intVal), @intlen)
    RETURN REPLICATE('0', @intLen - LEN(@intVal)) + CONVERT(nvarchar(10), @intVal)
END

Solution 7 - Sql Server

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'

Solution 8 - Sql Server

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...

Solution 9 - Sql Server

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)))

Solution 10 - Sql Server

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.

Solution 11 - Sql Server

    select right('000' + convert(varchar(3),id),3) from table
    
    example
    declare @i int
    select @i =1

select right('000' + convert(varchar(3),@i),3)

BTW if it is an int column then it will still not keep the zeros Just do it in the presentation layer or if you really need to in the SELECT

Solution 12 - Sql Server

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

Solution 13 - Sql Server

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

Solution 14 - Sql Server

Using RIGHT is a good option but you can also do the following:

SUBSTRING(CAST((POWER(10, N) + value) AS NVARCHAR(N + 1)), 2, N)

where N is the total number of digits you want displayed. So for a 3-digit value with leading zeros (N = 3):

SUBSTRING(CAST((POWER(10, 3) + value) AS NVARCHAR(4)), 2, 3)

or alternately

SUBSTRING(CAST(1000 + value) AS NVARCHAR(4)), 2, 3)

What this is doing is adding the desired value to a power of 10 large enough to generate enough leading zeros, then chopping off the leading 1.

The advantage of this technique is that the result will always be the same length, allowing the use of SUBSTRING instead of RIGHT, which is not available in some query languages (like HQL).

Solution 15 - Sql Server

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

Solution 16 - Sql Server

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

declare @val int,@len=800
select replace(str(@val,@len),' ','0')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRicardoBaldaView Question on Stackoverflow
Solution 1 - Sql ServerNguyen TranView Answer on Stackoverflow
Solution 2 - Sql ServerDarek.KView Answer on Stackoverflow
Solution 3 - Sql ServerKM.View Answer on Stackoverflow
Solution 4 - Sql ServerGoldBishopView Answer on Stackoverflow
Solution 5 - Sql ServerSedecimdiesView Answer on Stackoverflow
Solution 6 - Sql ServerC.ListView Answer on Stackoverflow
Solution 7 - Sql ServerBrute Force SQLView Answer on Stackoverflow
Solution 8 - Sql ServerPiotr NawrotView Answer on Stackoverflow
Solution 9 - Sql Serveruser2096582View Answer on Stackoverflow
Solution 10 - Sql ServerjhimesView Answer on Stackoverflow
Solution 11 - Sql ServerTarun GuptaView Answer on Stackoverflow
Solution 12 - Sql ServerJohn LonbergerView Answer on Stackoverflow
Solution 13 - Sql ServerMarciaView Answer on Stackoverflow
Solution 14 - Sql ServerPeter GluckView Answer on Stackoverflow
Solution 15 - Sql ServerJohnny DriesenView Answer on Stackoverflow
Solution 16 - Sql ServerNirenView Answer on Stackoverflow