简体   繁体   English

如何将前导零添加到现有列中?

[英]How to add leading zeros into existing Column?

I have one column ( zip varchar(10) ) in MySQL. 我在MySQL中有一栏( zip varchar(10) )。
I am giving some value examples of this columns. 我在此提供一些有价值的例子。

1. 576 1. 576
2. 5768 2. 5768
3. 57689 3. 57689

I want to replace all three digits with adding 00 as prefix, all four digits with adding 0 prefix. 我想用加00作为前缀替换所有三个数字,用加0前缀替换所有四个数字。
So after doing this operation my values should be, 因此,执行此操作后,我的值应该是

1. 00576 1. 00576
2. 05768 2. 05768
3. 57689 3. 57689

Is it possible with any MySQL query? MySQL查询有可能吗? Any ideas? 有任何想法吗?

The following query uses the LPAD function suggested by georstef. 以下查询使用georstef建议的LPAD函数。

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. 您可以为此使用存储过程,在过程内部检查CHAR_LENGTH() == 3(可以在此处使用变量而不是3),而不是使用if语句将前导零的数量设置为变量。 Than you could update the column with a concat function with the variable that has the leading zeros. 比起您可以使用concat函数更新具有前导零的变量的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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