我在创建Microsoft SQL Server中的表创建中包含的条件约束时遇到问题。我似乎无法弄明白。
我已尝试case
语句,if then
语句,似乎没有任何效果。
这是否可能,因为我一直收到语法错误?
CREATE TABLE SECTION
(
c# int FOREIGN KEY REFERENCES Course(c#),
se# int,
emp# int FOREIGN KEY REFERENCES Professor(EMP#),
class_time time,
controlNumber int DEFAULT 20,
CONSTRAINT pk_SectionID PRIMARY KEY (c#, se#),
CONSTRAINT chk_controlNumber CHECK (controlNumber >= 40 AND controlNumber <=60),
CONSTRAINT chk_c# CHECK (when c# between 3000 and 5000 then controlNumber <=40)
);
谢谢。
答案 0 :(得分:2)
你需要结合两个检查,否则它们会相互矛盾,然后只需将它们与简单的布尔逻辑结合起来:
CREATE TABLE SECTION(
c# int FOREIGN KEY REFERENCES Course(c#),
se# int,
emp# int FOREIGN KEY REFERENCES Professor(EMP#),
class_time time,
controlNumber int DEFAULT 20,
CONSTRAINT pk_SectionID PRIMARY KEY (c#, se#),
CONSTRAINT chk_controlNumber CHECK (
controlNumber between 40 AND 60 and (c# < 3000 or c# > 5000) or
(c# between 3000 and 5000 and controlNumber <= 40))
);