I want to implement a Check Constraint across a date range and foreign key.
I have a table created as:
- Primary Key
- Foreign Key
- DateStart
- DateEnd
The ForeignKey can appear many times in the table as long as there is a value in the EndDate. But there should only ever be one entry for the ForeignKey where the DateEnd is Null (the active version).
Apologies if this is simple, but I've been trying to use SQL Server GUI to put in an Constraint expression, but I can't get it to work.
Any help, or pointers to help would be appreciated.
Best Answer
You can do this with a unique filtered index.
Table setup.
Add the unique index on
FK
filtered onDateEnd is null
.Add one row to
OtherTable
.Add a couple of rows to
YourTable
.Add another row with a value in
DateEnd
will work just fine.Add a second row with
null
inDateEnd
will fail.Create Filtered Indexes
Create Unique Indexes
When scripting indexes from SSMS: