sqlserver 实现伪序列
在sqlserver生成对应格式的订单号 比如 P + 年月日+业务ID +序列。
订单号规则有两种:
单号生成规则:P+当天日期(年月日)+零售商注册序号+0000;
单一商品订单流水号: P+当天日期(年月日)+批发部注册序号+零售商注册序号+0000
思路
1. 生成 0000 --> 9999之间的伪序列
a. 新建一张序列表
b. 模拟oracle中的序列自增长
2. 用伪序列 + 规则生成订单号
创建 序列表
1 create table seqTable --序列表 2 ( 3 sellerId int, 4 buyerId int, 5 createDate varchar(20), --日期 6 curSeqNo varchar(20) --当前序号 7 )
生成序列过程
1 /* 2 获取序列 3 */ 4 create procedure getSeqNo(@sid int, -- 卖家店铺ID 5 @bid int, -- 买家店铺ID 6 @res varchar(20) output 7 ) -- 返回序列号 00001 8 as 9 10 declare @curSeqNo varchar(20), -- 序列号 11 @curSysDate varchar(20), -- 系统日期 12 @curNo int -- 序列 13 14 set @curSysDate = CONVERT(varchar(100), GETDATE(), 112); 15 if (@bid is null) 16 return ('-1') 17 18 -- 卖家、买家的ID都不空 19 if (@bid is not null and @sid is not null) 20 select @curSeqNo = curSeqNo from seqTable where sellerId=@sid and buyerId=@bid and createDate=@curSysDate 21 else 22 select @curSeqNo = curSeqNo from seqTable where buyerId=@bid and createDate=@curSysDate 23 24 -- 创建新的序列 25 if (@curSeqNo is null) 26 begin 27 set @curSeqNo = '0001'; 28 insert into seqTable(sellerId, buyerId, createDate,curSeqNo) 29 values (@sid, @bid,@curSysDate,@curSeqNo); 30 end 31 else 32 begin 33 set @curNo = cast(@curSeqNo as int); 34 set @curNo = @curNo + 1; --递增 35 set @curSeqNo = REPLACE(STR(@curNo, 4), ' ', '0'); --格式化字符串 36 if (@bid is not null and @sid is not null) 37 update seqTable set curSeqNo = @curSeqNo where sellerId=@sid and buyerId=@bid and createDate=@curSysDate; 38 else 39 update seqTable set curSeqNo = @curSeqNo where buyerId=@bid and createDate=@curSysDate 40 end 41 set @res = @curSeqNo; 42
获取订单号的过程
1 /* 2 单号生成规则:P+当天日期(年月日)+批发部注册序号+零售商注册序号+0000; 3 单一商品订单流水号: P+当天日期(年月日)+批发部注册序号+零售商注册序号+0000+0000。 4 */ 5 6 create procedure getCurBillNo(@prefix varchar(20), 7 @sid int, --卖家店铺ID 8 @bid int, --买家店铺ID 9 @billNo varchar(1000) output --订单号 10 ) 11 12 as 13 declare @res varchar(100),@seqNo varchar(100),@curSysDate varchar(100) 14 15 if(@bid is null) 16 return('-1') 17 18 set @curSysDate = CONVERT(varchar(100), GETDATE(), 112); 19 20 if (@prefix is null) 21 set @res ='P'; 22 else 23 set @res = @prefix; 24 25 if(@sid is not null) 26 begin 27 execute getSeqNo @sid, @bid,@seqNo output 28 set @res = @res + @curSysDate+cast(@sid as varchar) + cast(@bid as varchar) + @seqNo; 29 end 30 else 31 begin 32 execute getSeqNo @sid, @bid,@seqNo output 33 set @res = @res +@curSysDate +cast(@bid as varchar) + @seqNo; 34 end 35 set @billNo = @res; 36
这里的程序,没有考虑 并发性,以及性能。仅仅是学习使用