如何將 MySQL 中的空字串更新至 NULL?


對此,可以使用 LENGTH(),因為如果長度為 0,則意味著字串是空的。在找到後,可以使用 UPDATE 命令中的 SET 子句將其設定為 NULL。我們首先建立一個表 −

mysql> create table DemoTable
(
   Name varchar(50)
);
Query OK, 0 rows affected (0.68 sec)

使用 insert 命令向表中插入一些記錄 −

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)

更新於: 01-Oct-2019

1K+ 瀏覽量

開啟您的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.