【发布时间】:2015-09-05 00:43:18
【问题描述】:
我有下表:
CREATE TABLE dbo.myTable]
(
ID1 [int] NOT NULL,
ID2 [int] NOT NULL,
StartDate smalldatetime NOT NULL,
EndDate smalldatetime NULL,
CONSTRAINT [PK_myTable1] PRIMARY KEY CLUSTERED (ID1 ASC, ID2 ASC, StartDate ASC)
) ON [PRIMARY]
我想确保每个 ID1 和 ID2 的 StartDate 到 EndDate 期间是唯一的,并且没有重叠。
如何创建这样的检查约束:
(
ID1 <> existingRow.ID1
or ID2 <> existingRow.ID2
)
or (
ID1 = existingRow.ID1
and ID2 = existingRow.ID2
and (
StartDate >= isnull(existingRow.EndDate, Startdate + 1)
or isnull(EndDate, existingRow.StartDate + 1) <= existingRow.StartDate
)
)
...或具有如下条件的约束:
IF ID1 = existingRow.ID1 and ID2 = existingRow.ID2
CHECK (
StartDate >= isnull(existingRow.EndDate, Startdate + 1)
or isnull(EndDate, existingRow.StartDate + 1) <= existingRow.StartDate
)
提前谢谢...
【问题讨论】:
-
您必须使用触发器进行此类验证
-
我不太了解您的伪代码,但您实际上是在寻找temporal table 吗?也就是说,在任何给定的时刻,给定的
ID1、ID2组合只有一个“有效”行? -
如果是这样,您可能会发现this answer很有用
-
我将尝试 ughai 的“在插入/更新触发器之前”的想法。谢谢... ;)
-
我链接到的答案似乎比“仅”使用触发器更有效,但具有实际正确性已在表上的约束中建模的优点。该答案中的触发器只是隐藏了一些移动部件。
标签: sql-server tsql constraints