看看我的答案:sql server: generate primary key based on counter and another column value
出于您的目的,您可以这样定义您的公司表:
create table dbo.company
(
id int not null primary key ,
name varchar(32) not null unique ,
order_counter not null default(0) ,
...
)
以及您的订单表:
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 ) ,
)
并设置您的“添加订单”查询:
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 )
您没有并发(竞争)条件:“联锁更新”负责处理。此外,您还没有对数据库设计进行非规范化(第一种范式要求每个行和列的交集都是原子的/不可分解的:它只包含来自适用域的一个值,仅包含一个值。像您这样的复合标识符是禁止的。)
简单的!