DB2唯一流水號生成
最近開發的系統要求生成很多唯一的單證號,單證號的規則 前綴_yyyyMMdd+順序號,如 P_201210160001, P_201210160002。
因為生成多種的單證號。於是在系統中建了一個單證號種子表BAS_SEQ_SEED
www.2cto.com
ID (PK)
主鍵ID
BIGINT
NET_ID
網絡ID
BIGINT
COMP_ID
加盟公司ID
BIGINT
SEED_TYPE
種子類型
SMALLINT
SEED_DATE
日期
VARCHAR(16)
SEED_VALUE
種子值
SMALLINT
SEED_PREFIX
種子前綴
VARCHAR(6)
SEED_SPLIT
種子分隔符
VARCHAR(2)
CREATE_TIME
VARCHAR(19)
其中NET_ID、COMP_ID、SEED_TYPE建立一個唯一索引
www.2cto.com
生成的單證號有存儲過程來實現
Sql代碼
drop PROCEDURE PROC_SEQ_SEED_GET
select * FROM BAS_SEQ_SEED
CREATE PROCEDURE PROC_SEQ_SEED_GET
( IN net_id_in bigint, --網絡ID
IN comp_id_in bigint, --加盟公司ID
IN seed_type_in integer,--序列號類型
IN seed_date_in VARCHAR(16),--當前日期yyyymmdd格式
OUT return_value VARCHAR(32) --返回值
)
P1: BEGIN
DECLARE seed_value_t integer;
DECLARE seed_date_t varchar(16);
DECLARE return_value_t integer DEFAULT 1;
DECLARE rs1 CURSOR WITH RETURN FOR
select SEED_VALUE,SEED_DATE FROM BAS_SEQ_SEED as t where t.NET_ID=net_id_in and t.COMP_ID=comp_id_in and t.SEED_TYPE=seed_type_in for update;
OPEN rs1;
FETCH rs1 into seed_value_t ,seed_date_t;
IF (seed_value_t is null) then --表記錄不存在
begin
insert INTO BAS_SEQ_SEED(ID,NET_ID,COMP_ID,SEED_TYPE,SEED_DATE,SEED_VALUE)
VALUES
(NEXTVAL FOR SE_EXPRESSBAS,net_id_in,comp_id_in,seed_type_in,seed_date_in,1);
commit;
SET return_value_t = 1;
end;
else
begin
--set seed_date_in= SCM_WULIU.ts_fmt(current timestamp,'yyyymmdd');
if(seed_date_in=seed_date_t) then --當天
begin
update BAS_SEQ_SEED set SEED_VALUE=SEED_VALUE+1 where NET_ID=net_id_in and COMP_ID=comp_id_in and SEED_TYPE=seed_type_in;
SET return_value_t = seed_value_t+1;
end;
else --非當天
begin
update BAS_SEQ_SEED set SEED_DATE=seed_date_in,SEED_VALUE=1 where NET_ID=net_id_in and COMP_ID=comp_id_in and SEED_TYPE=seed_type_in;
SET return_value_t = 1;
end;
end if;
end;
end if;
if(return_value_t<10) then
set returnvalue=seed_date_in ||'000'||char(return_value_t);
elseif(return_value_t>=10 AND return_value_t<100) then
set returnvalue=seed_date_in ||'00'||char(return_value_t);
elseif(return_value_t>=100 AND return_value_t<1000) then
set returnvalue=seed_date_in ||'0'||char(return_value_t);
end if;
close rs1;
END P1
大數據量並發測試生成流程號唯一。
java調用存儲過程
www.2cto.com
Java代碼
try {
Session session = this.getHibernateSession();
String sql ="{call SCM_WULIU.PROC_SEQ_SEED_GET(?,?,?,?,?)}";
CallableStatement cs = session.connection().prepareCall(sql);// 存儲過程調用
cs.setLong(1, net_id);
cs.setLong(2, comp_id);
cs.setShort(3, seed_type);
cs.setString(4,PubMethod.getCurSysDate("yyyyMMdd"));
cs.registerOutParameter(5, Types.CHAR);
cs.execute();
result = cs.getString(5); //得到輸出參數
session.flush();
} catch (Exception he) {
throw he;
} finally {
closeSession();
}