為 MySQL 中現有列設定 NOT NULL 屬性


要為現有列設定 NOT NULL 屬性,請使用 ALTER TABLE 命令。我們先建立一個表 -

mysql> create table DemoTable1949
   (
   UserId int,
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

這是一個為現有列設定 NOT NULL 屬性的查詢 -

mysql> alter table DemoTable1949 modify UserName varchar(20) not null;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

讓我們查看錶的描述 -

mysql> desc DemoTable1949;

這將產生以下輸出 -

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| UserId   | int(11)     | YES  |     | NULL    |       |
| UserName | varchar(20) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable1949 values(101,NULL);
ERROR 1048 (23000): Column 'UserName' cannot be null
mysql> insert into DemoTable1949 values(101,'Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1949 values(102,'Bob');
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable1949;

這將產生以下輸出 -

+--------+----------+
| UserId | UserName |
+--------+----------+
|    101 | Chris    |
|    102 | Bob      |
+--------+----------+
2 rows in set (0.00 sec)

更新於: 31-Dec-2019

229 次瀏覽

啟動你的職業

完成課程獲取認證

開始
廣告