take a look at my answer here: sql server: generate primary key based on counter and other column value
For your purposes, you could define your company table as follows:
create table dbo.company ( id int not null primary key , name varchar(32) not null unique , order_counter not null default(0) , ... )
and your order table like this:
create table dbo.order ( company_id int not null foreign key references dbo.company( id ) , id int not null , order_number as 100000*company_id + id , ... constraint order_AK01 unique nonclustere ( order_number ) , constraint order_PK01 primary key clustered ( company_id , id ) , )
And configure the βadd orderβ request this way:
declare @new_order_number int update dbo.company set @new_order_number = dbo.company.order_counter + 1 , order_counter = dbo.company.order_counter + 1 where dbo.company.id = @some_company_id insert dbo.order ( company_id , id ) value ( @some_company_id , @new_order_number )
You have no concurrency conditions (race): this "blocked update" will take care of this. In addition, you did not denormalize the database design (the 1st normal form requires that each row and column intersection be atomic / indecomposable: it contains exactly one value from the applicable domain and nothing else. Suitable identifiers like yours are verboten.)
Easy!
source share