简体   繁体   中英

How to add leading zeros into existing Column?

I have one column ( zip varchar(10) ) in MySQL.
I am giving some value examples of this columns.

1. 576
2. 5768
3. 57689

I want to replace all three digits with adding 00 as prefix, all four digits with adding 0 prefix.
So after doing this operation my values should be,

1. 00576
2. 05768
3. 57689

Is it possible with any MySQL query? Any ideas?

The following query uses the LPAD function suggested by georstef.

UPDATE <tablename>
SET zip = LPAD(zip,5,'0');

You could use a stored procedure for this, inside your procedure check if CHAR_LENGTH() == 3 (you could use a variable instead of hardwiring 3 here)than use an if statement to set number of leading zeros to a variable. Than you could update the column with a concat function with the variable that has the leading zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM