使一個日期列變為 NULL 的 MySQL 查詢?


要使一個日期列變為 null,請使用 ALTER TABLE 和 MODIFY 並且將該日期設為 NULL。以下是語法 −

alter table yourTableName modify column yourColumnName date NULL;

讓我們首先建立一個表。此處,我們將該列設為 NOT NULL −

mysql> create table DemoTable
(
   ShippingDate date NOT NULL
);
Query OK, 0 rows affected (0.78 sec)

現在,在上述表中插入 NULL 值。由於我們將該列設為 NOT NULL,將會產生一個錯誤 −

mysql> insert into DemoTable values(null);
ERROR 1048 (23000) − Column 'ShippingDate' cannot be null

現在,讓我們修改該表並在上述表中允許 NULL −

mysql> alter table DemoTable modify column ShippingDate date NULL;
Query OK, 0 rows affected (1.81 sec)
Records : 0 Duplicates : 0 Warnings : 0

現在,再次嘗試使用 insert 命令在上述表中插入 NULL。由於我們修改了該表以接受 NULL,因此不會產生錯誤 −

mysql> insert into DemoTable values(null);
Query OK, 1 row affected (1.21 sec

使用 select 語句顯示該表中的所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+--------------+
| ShippingDate |
+--------------+
| NULL         |
+--------------+
1 row in set (0.00 sec)

更新於: 2019-10-10

2K+ 瀏覽

開啟你的職業生涯

透過完成課程認證

開始
廣告
© . All rights reserved.