Suppose the table with two columns:
ParentEntityId int foreign key
Number int
ParentEntityId is a foreign key to another table.
Number is a local identity, i.e. it is unique within single ParentEntityId.
Uniqueness is easily achieved via unique key over these two columns.
How to make Number be automatically incremented in the context of the ParentEntityId on insert?
Addendum 1
To clarify the problem, here is an abstract.
ParentEntity has multiple ChildEntity, and each ChiildEntity should have an unique incremental Number in the context of its ParentEntity.
Addendum 2
Treat ParentEntity as a Customer.
Treat ChildEntity as an Order.
So, orders for every customer should be numbered 1, 2, 3 and so on.
Well, there’s no native support for this type of column, but you could implement it using a trigger:
Not tested but I’m pretty sure it’ll work. If you have a primary key, you could also implement this as an
AFTERtrigger (I dislike usingINSTEAD OFtriggers, they’re harder to understand when you need to modify them 6 months later).Just to explain what’s going on here:
SERIALIZABLEis the strictest isolation mode; it guarantees that only one database transaction at a time can execute these statements, which we need in order to guarantee the integrity of this “sequence.” Note that this irreversibly promotes the entire transaction, so you won’t want to use this inside of a long-running transaction.The CTE picks up the highest number already used for each parent ID;
ROW_NUMBERgenerates a unique sequence for each parent ID (PARTITION BY) starting from the number 1; we add this to the previous maximum if there is one to get the new sequence.I probably should also mention that if you only ever need to insert one new child entity at a time, you’re better off just funneling those operations through a stored procedure instead of using a trigger – you’ll definitely get better performance out of it. This is how it’s currently done with
hierarchyidcolumns in SQL ’08.