I have a field that is varchar(8)
, holding date values that I converted from float
to varchar
.
Some records have eight characters, and some have seven. I would like to make them all the same length by adding a leading zero to the ones that have 7.
8 char example: 12162003
7 char example: 5072004 (needs a leading zero)
The query:
select birthdate_new from table_name
Oracle. 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.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
An Auto-incremented column with VARCHAR / NVARCHAR data type in SQL can be done using a computed column. A computed column is a column that expresses the data that can be used by an other column in the same table. This expression can be non-computed columns or any function and constant.
A function that will work for more situations would be REPLICATE. It concatenates a value X amount of times to a string.
SELECT REPLICATE('0', 8-LEN(birthdate_new)) + birthdate_new AS 8_len_birthdate
This will take the length of your birthdate, subtract it from 8, then put that many leading 0's on the front to make it 8 chars.
You can use RIGHT
:
SELECT RIGHT('00000000' + birthdate_new, 8) AS birthdate_new
FROM table_name;
LiveDemo
If you want to UPDATE
field use:
UPDATE table_name
SET birthdate_new = RIGHT('00000000' + birthdate_new, 8)
WHERE LEN(birthdate_new) < 8;
As its always 7/8 you could:
select right('0' + fld, 8)
or
select case when len(fld) = 7 then '0' else '' end + fld
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