Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add leading zero when number is less than 10?

Tags:

sql

sql-server

I have a column in my sql table. I am wondering how can I add leading zero to my column when my column's value is less than 10? So for example:

number   result
1     ->    01
2     ->    02
3     ->    03
4     ->    04
10    ->    10
like image 754
RedRocket Avatar asked Apr 29 '16 06:04

RedRocket


People also ask

How do you add leading zeros when a number is less than 10 in SQL?

Oracle has a TO_CHAR(number) function that allows us to add leading zeros to a number. It returns its result as a string in the specified format. The 0 format element is what outputs the leading zeros. If we didn't want leading zeros, we could use 9 .

How do you add leading zeros when a number is less than 10 in PHP?

php $num = 4; $num_padded = sprintf("%02d", $num); echo $num_padded; // returns 04 ?> It will only add the zero if it's less than the required number of characters.


2 Answers

format(number,'00')

Version >= 2012

like image 73
CrimsonKing Avatar answered Sep 27 '22 23:09

CrimsonKing


You can use RIGHT:

SELECT RIGHT('0' + CAST(Number AS VARCHAR(2)), 2) FROM tbl

For Numbers with length > 2, you use a CASE expression:

SELECT
    CASE
        WHEN Number BETWEEN 0 AND 99
            THEN RIGHT('0' + CAST(Number AS VARCHAR(2)), 2)
        ELSE
            CAST(Number AS VARCHAR(10))
    END
 FROM tbl
like image 35
Felix Pamittan Avatar answered Sep 27 '22 23:09

Felix Pamittan