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
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 .
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.
format(number,'00')
Version >= 2012
You can use RIGHT
:
SELECT RIGHT('0' + CAST(Number AS VARCHAR(2)), 2) FROM tbl
For Number
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With