为 MySQL 列添加前导零?
要添加前导零,可以使用 LPAD()。我们首先创建一个表 −
mysql> create table DemoTable ( Code varchar(100) ); Query OK, 0 rows affected (0.87 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('JS'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('CB'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('DM'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('CT'); Query OK, 1 row affected (0.07 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
结果如下 −
+------+ | Code | +------+ | JS | | CB | | DM | | CT | +------+ 4 rows in set (0.00 sec)
现在,我们在 MySQL 中添加前导零 −
mysql> update DemoTable set Code=LPAD(Code, 8, '0'); Query OK, 4 rows affected (0.10 sec) Rows matched: 4 Changed: 4 Warnings: 0
让我们再次检查表记录 −
mysql> select *from DemoTable;
结果如下 −
+----------+ | Code | +----------+ | 000000JS | | 000000CB | | 000000DM | | 000000CT | +----------+ 4 rows in set (0.00 sec)
广告