简体   繁体   中英

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

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

The Format function can be used in SQL Server 2012 & 2014, but I'm using SQL Server 2008 R2. How I can get the same result?

Try this:

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

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

You can simply use Right function. check the below 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)

Considering only 0-9 needs 0 to be appended 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 

使用此代码

 SELECT CONVERT(varchar, CAST(987654321 AS money), 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM