Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
James Polhemus Avatar asked Dec 16 '09 13:12

James Polhemus


People also ask

How do you get a two digit number in SQL?

For this, you can use LPAD() and pad a value on the left.

How can I get two digit date in SQL?

SELECT RIGHT('0' + RTRIM(MONTH('12-31-2012')), 2);


2 Answers

select right ('00'+ltrim(str( <number> )),2 ) 
like image 101
Sparky Avatar answered Sep 27 '22 20:09

Sparky


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

declare @number int  = 1 select format (@number, '0#') 
like image 40
Alex Avatar answered Sep 27 '22 19:09

Alex