MySQL CHECK 約束
MySQL CHECK 約束
The CHECK
constraint is used to limit the value range that can be placed in a column.(CHECK 約束用於限制可以放入列中的值的範圍。)
If you define a CHECK
constraint on a column it will allow only certain values for this column.(如果在列上定義 CHECK 約束,它將只允許該列的特定值。)
If you define a CHECK
constraint on a table it can limit the values in certain columns based on values in other columns in the row.(如果在表上定義 CHECK 約束,它可以基於行中其他列的值來限制某些列中的值。)
CHECK on CREATE TABLE
The following SQL creates a CHECK
constraint on the "Age" column when the "Persons" table is created. The CHECK
constraint ensures that the age of a person must be 18, or older(以下 SQL 在建立 "Persons" 表時,在 "Age" 列上建立了一個 CHECK 約束。CHECK 約束確保一個人的年齡必須是 18 歲或以上。)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
To allow naming of a CHECK
constraint, and for defining a CHECK
constraint on multiple columns, use the following SQL syntax(要允許命名 CHECK 約束,以及為多個列定義 CHECK 約束,請使用以下 SQL 語法)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
CHECK on ALTER TABLE
To create a CHECK
constraint on the "Age" column when the table is already created, use the following SQL(要在表已建立後,在 "Age" 列上建立 CHECK 約束,請使用以下 SQL)
ALTER TABLE Persons
ADD CHECK (Age>=18);
To allow naming of a CHECK
constraint, and for defining a CHECK
constraint on multiple columns, use the following SQL syntax(要允許命名 CHECK 約束,以及為多個列定義 CHECK 約束,請使用以下 SQL 語法)
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
DROP a CHECK Constraint (刪除 CHECK 約束)
To drop a CHECK
constraint, use the following SQL(要刪除 CHECK 約束,請使用以下 SQL)
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;