CHECK约束用于定义列允许的格式和值。CHECK约束的语法如下;
CHECK (logical_Expression)
如果CHECK的逻辑表达式计算为TRUE,行就会被插入。如果CHECK约束的表达式计算为FALSE,行插入就会失败。
下面示例:
是向CREATE TABLE定义中增加一个CHECK约束。GPA列的值会被限制在某个数值范围之内:
USE AdventureWorks
GO
DROP TABLE Person.EmployeeEducationType
CREATE TABLE Person.EmployeeEducationType
(
EmployeeEducationTypeID int NOT NULL PRIMARY KEY,
EmployeeID int NOT NULL,
EducationTypeID int NULL,
GPA numeric(4,3) NOT NULL CHECK (GPA>2.5 AND GPA<=4.0)
)
CHECK约束表达式可以是在列约束级别定义。CHECK约束还能定义在表约束级别,并且允许在表达式中引用多个列:
USE AdventureWorks
GO
DROP TABLE Person.EmployeeEducationType
CREATE TABLE Person.EmployeeEducationType
(
EmployeeEducationTypeID int NOT NULL PRIMARY KEY,
EmployeeID int NOT NULL,
EducationTypeID int NULL,
GPA numeric(4,3) NOT NULL,
CONSTRAINT CK_EmployeeEducationType
CHECK (EducationTypeID > 1 AND GPA > 2.5 AND GPA <=4.0)
)