Suppose, I have a composite primary key that consists of 3 columns: [ShardKey], [SiteId] and [ServiceId]. Column [ServiceId] is an identity column and should start from 1 for a new combination of [ShardKey] and [SiteId], but SQL server fails - the column [ServiceId] never starts from 1, it just increments its value no matter what the primary key is. I did add constraint for primary key that holds all three columns. What should I do to make it start from 1 when a new combination of [ShardKey] and [SiteId] comes in?
[ShardKey] [SiteId] [ServiceId] [Name] 1009 1 1 Coffee 1009 1 2 Tea 1009 1 3 Cocaine 1009 2 1 Coffee 1009 2 2 Tea 1009 2 3 Cocaine 1010 1 1 Coffee 1010 1 2 Tea 1010 1 3 Cocaine That's what I want SQL server to do for me. Values for [ShardKey] and [SiteId] are known to me, so I can always insert them into SQL script, but I need the column [ServiceId] to start from 1 for a new combination of [ShardKey] and [SiteId]
IDENTITYdoes. anIDENTITYincrements every time anINSERTis attempted. It doesn't care about the values of the other columns.SEQUENCEobjects (one for each combination ofShardKeyandSiteId?) and then use the appropriateSEQUENCE. Of course, if you have a lot of different values forShardKeyandSiteId, that isn't a maintainable solution.CreationDatemight be a good candidate for a clustered index here); conversely; it might be that you're happy to pay the insert/shuffle cost of clustering on the PK, in order to get the benefits of reduced page fetches when fetching all for shard/shard+site