How do I format the number in T-SQL for SQL Server 2008 R2?

select FORMAT(5,'0#')   --05
select FORMAT(11,'0#')   --11

      

The function Format

can be used in SQL Server 2012 and 2014, but I am using SQL Server 2008 R2. How can I get the same result?

+3


source to share


3 answers


Considering only 0-9 needs to be added before.



Declare @num int =5

SELECT CASE 
         WHEN Len(@num) = 1 THEN '0' + Cast(@num AS VARCHAR(10)) 
         ELSE Cast(@num AS VARCHAR(10)) 
       END 

      

+2


source


Try the following:



SELECT right('0' + convert(varchar,5),2) --05

SELECT right('0' + convert(varchar,11),2) --11

      

+4


source


You can just use the right function. check the following methods:

/* Method 1 Using RIGHT function*/

SELECT RIGHT('00' + cast(9 as varchar(5)), 2)


/* Method 2 Using RIGHT AND REPLICATE function*/

SELECT RIGHT(REPLICATE('0', 2) + cast(9 as varchar(5)), 2)

      

+2


source







All Articles