Check constraint on grouped conditions
0
votes
0
answers
76
views
Take the following table as an example:
GroupID AlphaID BetaID
1 0 1
1 1 1
1 2 2
2 0 1
2 1 2
2 2 2
2 3 2
3 0 1
3 1 1
I would like to write a check constraint that checks the following:
**1. AlphaID - Check Constraint**
- The first instance of
AlphaID
in a GroupID
must start at 0
- E.g inserting *GroupID = 4* with an *AlphaID = 0* will succeed
- E.g inserting *GroupID = 4* with an *AlphaID = 1* will fail
- AlphaID
must be unique within each GroupID
and must be +1 greater than current max AlphaID
- E.g inserting *GroupID = 3* with an *AlphaID = 1* will fail (duplicate)
- E.g inserting *GroupID = 3* with an *AlphaID = 2* will succeed (current max + 1)
- E.g inserting *GroupID = 3* with an *AlphaID = 4* will fail (out of order)
**2. BetaID - Check Constraint**
- The first instance of BetaID
in a GroupID
must start at 1
- E.g inserting *GroupID = 4* with an *BetaID = 0* will fail
- E.g inserting *GroupID = 4* with an *BetaID = 1* will succeed
- BetaID
can have duplicates within GroupID
or may be +1 greater than current max BetaID
- E.g inserting *GroupID = 3* with an *BetaID = 1* will succeed
- E.g inserting *GroupID = 3* with an *BetaID = 2* will succeed
- E.g inserting *GroupID = 3* with an *BetaID = 4* will fail (out of order)
**A solution that uses a trigger may also be suitable.**
Asked by Levi
(43 rep)
May 12, 2020, 05:37 AM