[tsql] T-SQL Format integer to 2-digit string

I can't find a simple way to do this in T-SQL.

I have for example a column (SortExport_CSV) that returns an integer '2' thru 90. If the stored number is a single digit, I need it to convert to a 2 digit string that begins with a 0. I have tried to use CAST but I get stuck on how to display the style in the preferred format (0#)

Of course it is easy to do this on the front end (SSRS, MSAccess, Excel, etc) but in this instance I have no front end and must supply the raw dataset with the already formatted 2 digit string.

This question is related to tsql format casting

The answer is


try

right('0' + convert(varchar(2), @number),2)

You can use T-SQL's built in format function:

declare @number int  = 1
select format (@number, '0#')

You can create a function like this:

CREATE FUNCTION [dbo].[f_convert_int_to_2_digits](@input int)
RETURNS varchar(10)
AS
BEGIN
    --return value
    DECLARE @return varchar(10)

    if @input < 10
    begin
    set @return = '0' + convert(varchar(1), @valor)
end
    else
    begin
        set @return = convert(varchar(10), @input)
    end

    -- return result
    RETURN @return

END

and then use it everywhere:
select [dbo].[f_convert_int_to_2_digits](<some int>)


Try this

--Generate number from 2 to 90

;with numcte as(
select 2 as rn
union all
select rn+1 from numcte where rn<90)

--Program that formats the number based on length

select case when LEN(rn) = 1 then '00'+CAST(rn as varchar(10)) else CAST(rn as varchar(10)) end number
from numcte

Partial Output:

number    
002
003
004
005
006
007
008
009
10
11
12
13
14
15
16
17
18
19
20

Here is tiny function that left pad value with a given padding char You can specify how many characters to be padded to left..

   Create    function fsPadLeft(@var varchar(200),@padChar char(1)='0',@len int)
      returns varchar(300)
    as
    Begin
      return replicate(@PadChar,@len-Len(@var))+@var
    end

To call :

declare @value int; set @value =2
select dbo.fsPadLeft(@value,'0',2)

SELECT RIGHT('0' + CAST(sortexport_csv AS VARCHAR), 2)
FROM your_table

here you go

select RIGHT(REPLICATE('0', 2) + CAST(2 AS VARCHAR(2)), 2)

should return 02


DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO

Another example:

select 
case when teamId < 10 then '0' + cast(teamId as char(1)) 
else cast(teamId as char(2)) end      
as 'pretty id',
* from team

SELECT
replace(str(month(DATEADD(month, -1, '2012-02-29')), 2),' ' , '0')

DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO

Example for converting one digit number to two digit by adding 0 :

DECLARE @int INT = 9 
        SELECT CASE WHEN @int < 10
                    THEN FORMAT(CAST(@int AS INT),'0#')
               ELSE 
                   FORMAT(CAST(@int AS INT),'0')
               END

You could try this

SELECT RIGHT( '0' + convert( varchar(2) , '0' ),  2 ) -- OUTPUTS : 00
SELECT RIGHT( '0' + convert( varchar(2) , '8' ),  2 ) -- OUTPUTS : 08
SELECT RIGHT( '0' + convert( varchar(2) , '9' ),  2 ) -- OUTPUTS : 09
SELECT RIGHT( '0' + convert( varchar(2) , '10' ), 2 ) -- OUTPUTS : 10
SELECT RIGHT( '0' + convert( varchar(2) , '11' ), 2 ) -- OUTPUTS : 11

this should help


Convert the value to a string, add a zero in front of it (so that it's two or tree characters), and get the last to characters:

right('0'+convert(varchar(2),Sort_Export_CSV),2)

You're all doing too much work:

right(str(100+@x),2)

-- for a function, same idea: 
--
create function zeroPad( @yourNum int, @wid int)
as 
begin
  return right( 1000000+@yourNum), @wid)
end

select right ('00'+ltrim(str( <number> )),2 )

The simplest way is:

declare
    @len int = 10,
    @number int = 122222,
    @prefix char = '0'

select replicate(@prefix, @len - len(@number)) + CAST(@number AS VARCHAR)

result:

0000122222


Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY