日期:2014-05-17  浏览次数:20554 次

设计主键
你好
需要设计订单表的主键,要求是年月日+(每新单自增1)
例如 201307081 201307082,
identity(getdate(),1),这种方式可行吗?

------解决方案--------------------
生成订单编号,可以使用一个存储过程返回,然后在这个字段上建立key,这个逻辑不是identity(getdate(),1)能够实现的,需要写一个Store procedure  ,生成返回字符串。

------解决方案--------------------
这个不是主键设计,而是主键值的问题,这个依靠sql代码去控制
------解决方案--------------------

create table t
(
id int identity(1,1) primary key,
OrderId as replace(convert(varchar(10),getdate(),120),'-','')+right('00000000'+ltrim(id),8),
Others varchar(20)
)
go
insert t(Others)
select 'a' union all
select 'b' union all
select 'c' 
go

select * from t

drop table t
/*
id OrderId Others
--------------------------------
1 2013070800000001 a
2 2013070800000002 b
3 2013070800000003 c
*/

------解决方案--------------------
如果多并发,最好还是通过一个存储过程来进行控制。