一个表中的列之间的关系

时间:2016-07-10 08:04:27

标签: sql-server database constraints nullable

我有以下表格:

Create table Rent
(
Id int not null,
Id_car int not null,
Date_rent date not null,
Date_return date,
Id_pleace_rent int not null,
Id_pleace_return int
)

我想添加约束,如果在列#34; Date_return"中的同一行中然后在列" Id_pleace_return"中为NULL也必须为NULL。我该怎么做?

2 个答案:

答案 0 :(得分:3)

ALTER TABLE dbo.Rent
ADD CONSTRAITN CK_Rent_Verify_Return
CHECK(
    Date_return IS NULL AND Id_pleace_return IS NULL 
    OR Date_return IS NOT NULL -- AND Id_pleace_return IS NOT NULL 
)

答案 1 :(得分:0)

现在这是SQL服务器,因此它应该是这些内容:

ALTER TABLE Rent
ADD CONSTRAINT Nullability
CHECK (
(CASE WHEN Date_return IS NULL AND Id_pleace_return IS NOT NULL THEN 0 ELSE 1 END

)
GO
相关问题