问题
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