SQL CHECK约束问题

时间:2010-04-16 11:35:55

标签: sql sql-server sql-server-2008 constraints check-constraints

我正在使用SQL Server 2008,我有一个包含三列的表:LengthStartTimeEndTime。我想在这个表上做一个CHECK约束,说明:

if Length == NULL then
  StartTime <> NULL and EndTime <> NULL
else
  StartTime == NULL and EndTime == NULL

我开始尝试这样的事情:

Length == NULL AND StartTime <> NULL AND EndTime <> NULL

显然这还不够,但即便是这个简单的表达也无法验证。我收到错误:

“验证'CK_Test_Length_Or_Time'时出错。是否要编辑约束?”

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:4)

CHECK ([Length] IS NULL AND [StartTime] IS NOT NULL AND [EndTime] IS NOT NULL
      OR [Length] IS NOT NULL AND [StartTime] IS NULL AND [EndTime] IS NULL))

答案 1 :(得分:3)

SQL Server中没有==运算符。检查null时,您必须使用“is”

请试试这个:

((Length is null AND starttime is not null AND endtime is not null) OR
(Length is not null AND starttime is null AND endtime is null))

HTH