假设我把它作为一个表:
InvoiceDetailId (int, not null, PK),
InvoiceId (int, not null, FK),
InvoiceNumber (varchar(50), null),
EndEffectiveTime (datetime, null)
如何在此表上编写检查约束,以确保表中的每个发票只有一个记录的空EndEffectiveTime(意味着它是活动详细记录)?
所以基本上这个查询可以从不返回结果:
SELECT InvoiceId
FROM InvoiceDetails
GROUP BY InvoiceId, EndEffectiveTime
HAVING (EndEffectiveTime IS NULL)
AND (COUNT(InvoiceDetailId) <> 1);
答案 0 :(得分:2)
您可以使用唯一的过滤索引。
create unique index UX_InvoiceDetails_InvoiceId on InvoiceDetails(InvoiceID)
where EndEffectiveTime is null