5.check限制(條件限制)
描述:check限制用于限制列中的值的範圍。
如果對單個列定義check限制,那麼該列隻允許特定的值。
如果對一個表定義check限制,那麼此限制會在特定的列中對值進行限制。
資料庫:My SQL
文法:
create table persons
(
id int not null,
name varchar(255) not null,
check(id>0)
)
---id這個列的值不可以小于0,條件限制
資料庫:SQL Servers/Oracle/MS Access:
文法:
create table persons
(
id int not null check(id>0),
name varchar(255)
)
---id這個列的值不可以小于0,條件限制
如果需要命名check限制,以及為多個定義check限制,請使用下面的sql文法:
資料庫:MySQL/SQL Server/Oracle/MS Access:
create table persons
(
id int not null,
address varchar(255),
constraint chk_person check (id>0 and address="chengdu")
)
---id這個列的值不可以小于0,address必須為“chengdu”,條件限制
如果在表存在的情況下為“id”列建立checke限制,請使用下面的sql:
資料庫:MySQL/SQL Server/Oracle/MSAccess:
alter table persons add check(id>0)
---id這個列的值不可以小于0,條件限制
如果需要命名check限制,以及為多個列定義check限制,請使用下面的sql語句:
資料庫:MySQL/SQL Server/Oracle /MS Access:
alter table persons add constraint chk_person check (id>0 and address="chengdu")
---id這個列的值不可以小于0,address必須為“chengdu”,條件限制
撤銷check限制:
資料庫:SQL Server/Oracle/MS Access
文法:
alter table persons drop constraint chk_person
資料庫:MySQL
alter table persons drop check chk_person