Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeros to a varchar field [duplicate]

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 
like image 411
john french Avatar asked Dec 04 '15 17:12

john french


People also ask

How do you add leading zeros to a string in SQL?

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.

How do you add leading zeros to a string?

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.

Can you auto increment a varchar value in SQL Server?

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.


3 Answers

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.

like image 113
dfundako Avatar answered Oct 28 '22 23:10

dfundako


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;
like image 13
Lukasz Szozda Avatar answered Oct 29 '22 01:10

Lukasz Szozda


As its always 7/8 you could:

select right('0' + fld, 8)

or

select case when len(fld) = 7 then '0' else '' end + fld
like image 2
Alex K. Avatar answered Oct 29 '22 01:10

Alex K.