I have a table of identifiers, IntervalFrom and IntervalTo:
| Identifier | IntervalFrom | IntervalTo |
|---|---|---|
| 1 | 0 | 2 |
| 1 | 2 | 4 |
| 2 | 0 | 2 |
| 2 | 2 | 4 |
I already have a trigger to NOT allow the intervals to overlap.
I am looking for a trigger or constraint that will not allow data gaps. I have search and the information I found relates to gaps in queries and data rather than not allowing them in the first place. I am unable to find anything in relation to this as a trigger or constraint.
Is this possible using T-SQL?
Thanks in advance.
You can construct a table that automatically is immune from overlaps and gaps:
Note, this does require a slightly different convention for you first and last intervals - they need to use
nullrather than0or the (somewhat arbitrary)4.Note also that modifying data in such a table can be a challenge - if you're inserting a new interval, you also need to update other intervals to accommodate the new one.
MERGEis your friend here.Given the above, we can insert your (modified) sample data:
But we cannot insert an overlapping value (this errors):
You should also see that the foreign keys prevent gaps from existing in a sequence