我正在尝试创建表格并根据以下条件对价格进行分类:
但我一直遇到错误
CREATE TABLE LabTest
(
testCode char(4) not null,
name char(40) not null,
category int not null,
price decimal(30,2) not null,
ageAppropriate int not null,
constraint testCode_PK PRIMARY KEY (testCode),
constraint age_CHK check (ageAppropriate >= 0),
);
ALTER TABLE LabTest
ADD CONSTRAINT Category_CHK
CHECK (CASE Category
WHEN Price BETWEEN 7 AND 20 THEN 1
WHEN Price BETWEEN 20 AND 50 THEN 2
WHEN Price BETWEEN 50 AND 100 THEN 3
WHEN Price BETWEEN 100 AND 350 THEN 4
ELSE 0
END);
答案 0 :(得分:4)
您需要对约束条件进行表述,因为come列值等于CASE
表达式:
ALTER TABLE LabTest
ADD CONSTRAINT Category_CHK CHECK
(
Category = CASE WHEN Price BETWEEN 7 AND 20 THEN 1
WHEN Price BETWEEN 20 AND 50 THEN 2
WHEN Price BETWEEN 50 AND 100 THEN 3
WHEN Price BETWEEN 100 AND 350 THEN 4
ELSE 0 END
);
旁注:CASE
表达式中的范围实际上是重叠的,因为BETWEEN
的两端都是包含端点的。因此,您编写的内容将与以下内容相同:
CASE WHEN Price >= 7 AND Price <= 20 THEN 1
WHEN Price > 20 AND Price <= 50 THEN 2
WHEN Price > 50 AND Price <= 100 THEN 3
WHEN Price > 100 AND Price <= 350 THEN 4
ELSE 0 END
如果以上不是您想要处理边界条件的方式,请根据需要更改逻辑。