How to create a check constraint that ensures one active detail record for a table?

我们两清 提交于 2019-12-13 19:14:10

问题


Let's say I have this as a table:

InvoiceDetailId  (int, not null, PK),
InvoiceId        (int, not null, FK),
InvoiceNumber    (varchar(50), null),
EndEffectiveTime (datetime, null)

How can I write a check constraint on this table that makes sure that for each invoice in the table there is only one record with a null EndEffectiveTime (meaning it's the active detail record)?

So basically this query can never return results:

SELECT   InvoiceId
FROM     InvoiceDetails
GROUP BY InvoiceId, EndEffectiveTime
HAVING   (EndEffectiveTime IS NULL)
         AND (COUNT(InvoiceDetailId) <> 1);

回答1:


You can use a unique filtered index.

create unique index UX_InvoiceDetails_InvoiceId on InvoiceDetails(InvoiceID) 
  where EndEffectiveTime is null

Create Unique Indexes
Create Filtered Indexes

SQL Fiddle



来源:https://stackoverflow.com/questions/22944288/how-to-create-a-check-constraint-that-ensures-one-active-detail-record-for-a-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!