如何在MySQL中将空字符串更新为NULL?

为此,请使用LENGTH(),因为如果长度为0,则表示字符串为空。找到之后,可以使用UPDATE命令中的SET子句将其设置为NULL。让我们首先创建一个表-

mysql> create table DemoTable
(
   Name varchar(50)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values('Chris');
mysql> insert into DemoTable values('');
mysql> insert into DemoTable values('David');
mysql> insert into DemoTable values('');

使用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;
Rows matched: 2 Changed: 2 Warnings: 0

让我们再次检查表记录-

mysql> select *from DemoTable;

这将产生以下输出-

+-------+
| Name  |
+-------+
| Chris |
| NULL  |
| David |
| NULL  |
+-------+
4 rows in set (0.00 sec)
猜你喜欢