检查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)
阅读更多:MySQL 教程