在 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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP