如何在MySQL中将空字符串更新为NULL?
为此,请使用LENGTH(),因为如果长度为0,则表示字符串为空。找到后,您可以使用UPDATE命令中的SET子句将其设置为NULL。让我们首先创建一个表 –
mysql> create table DemoTable
(
Name varchar(50)
);
Query OK, 0 rows affected (0.68 sec)
使用插入命令在表中插入一些记录 –
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('');
Query OK, 1 row affected (0.15 sec)
使用SELECT语句从表中显示所有记录 –
mysql> select *from DemoTable;
这将产生以下输出 –
+-------+
| Name |
+-------+
| Chris |
| |
| David |
| |
+-------+
4 rows in set (0.00 sec)
以下是将空字符串更新为NULL的查询 –
mysql> update DemoTable set Name=NULL where length(Name)=0;
Query OK, 2 rows affected (0.12 sec)
Rows matched: 2 Changed: 2 Warnings: 0
让我们再次检查表记录 –
mysql> select *from DemoTable;
这将产生以下输出 –
+-------+
| Name |
+-------+
| Chris |
| NULL |
| David |
| NULL |
+-------+
4 rows in set (0.00 sec)
阅读更多:MySQL 教程