SQL Server:无法添加约束

时间:2018-10-05 03:45:58

标签: sql-server constraints case between

我正在尝试创建表格并根据以下条件对价格进行分类:

  • 对于类别1,值的范围是7到20(含)。
  • 对于类别2,值的范围是20到50(含)。
  • 对于类别3,值的范围是50到100(含)。
  • 对于任何其他类别,值的范围是100到350(含)。

但我一直遇到错误

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);

1 个答案:

答案 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

如果以上不是您想要处理边界条件的方式,请根据需要更改逻辑。