在 SQL 中檢查表的一個欄位是否設定了 NOT NULL 屬性?


要檢查表的一個欄位是否具有 NOT NULL 屬性,可以使用以下兩種語法中的任何一種。第一個語法如下 -

desc yourTableName;

以下為第二個語法 -

select column_name,
   is_nullable
   from information_schema.columns
   where table_schema = ‘yourDatabaseName’
   and table_name = 'yourTableName’;

我們先看一個示例並建立一個表 -

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(40),
   StudentAge int NOT NULL,
   IsActiveStudent ENUM('ACTIVE",INACTIVE') NOT NULL,
   StudentCountryName varchar(40)
);
Query OK, 0 rows affected (1.53 sec)

第一個語法如下,用於檢查表字段是否設定了 NOT NULL 屬性 -

mysql> desc DemoTable;

這將產生以下輸出 -

+--------------------+--------------------------+------+-----+---------+----------------+
| Field              | Type                     | Null | Key | Default |          Extra |
+--------------------+--------------------------+------+-----+---------+----------------+
| StudentId          | int(11)                  | NO   | PRI | NULL    | auto_increment |
| StudentName        | varchar(40)              | YES  |     | NULL    |                |
| StudentAge         | int(11)                  | NO   |     | NULL    |                |
| IsActiveStudent    | enum('ACTIVE",INACTIVE') | NO   |     | NULL    |                |
| StudentCountryName | varchar(40)              | YES  |     | NULL    |                |
+--------------------+--------------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

第二個語法如下,用於檢查表字段是否設定了 NOT NULL 屬性 -

mysql> select column_name,
   is_nullable
   from information_schema.columns
   where table_schema = 'web'
   and table_name = 'DemoTable';

這將產生以下輸出 -

+--------------------+-------------+
| COLUMN_NAME        | IS_NULLABLE |
+--------------------+-------------+
| StudentId          | NO          |
| StudentName        | YES         |
| StudentAge         | NO          |
| IsActiveStudent    | NO          |
| StudentCountryName | YES         |
+--------------------+-------------+
5 rows in set (0.00 sec)

更新於: 10-Oct-2019

409 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.