如何将Check约束添加到数据库?

时间:2016-06-23 11:23:18

标签: sql-server-2014

我想将以下检查约束添加到名为“service”的表中,添加到“status”列

CREATE TABLE Service(
Service_ID INT(5) PRIMARY KEY NOT NULL,
Invoice_ID INT(5),
Project_ID INT(5) NOT NULL,
Description CHAR(20) NOT NULL,
Start_Date VARCHAR (10) NOT NULL,
Due_Date VARCHAR (10) NOT NULL,
Planned_Price VARCHAR (10),
Actual_Price VARCHAR (10),
Status CHAR (10) NOT NULL,
Date_Completed VARCHAR (10)
);

“status”列的内容/样本数据将从以下为1  计划,积极,完成

*如果有效或已完成:DueDate,StartDate和PlannedPrice都不为空 *如果已完成:DateCompleted和ActualPrice都不为空

2 个答案:

答案 0 :(得分:0)

这有助于

Status CHAR(10) NOT NULL CHECK (Status IN ('planned', 'active', 'completed'))

(Status like 'active' and DueDate NOT NULL AND StartDate not NULL)

答案 1 :(得分:0)

我没有测试过,
但这是第一个

ALTER TABLE Service WITH NOCHECK  
ADD CONSTRAINT CK_serice_one 
CHECK (
    (Status IN ('active','completed')
          AND DueDate IS NOT NULL
          AND StartDate IS NOT NULL
          AND PlannedPrice IS NOT NULL)
    OR Status NOT IN ('active','completed')
);

这是第二次

ALTER TABLE Service WITH NOCHECK  
ADD CONSTRAINT CK_serice_two
CHECK (
    (Status LIKE 'completed'
          AND DateCompleted IS NOT NULL
          AND ActualPrice IS NOT NULL)
    OR Status NOT LIKE 'completed'
);