生成的订单编号类似:
CREATE DEFINER=`root`@`%` PROCEDURE `p`(IN table_name varchar(50),IN filed_name varchar(50) ,IN orderNamePre varchar(10) ,in num INT )
BEGIN
DECLARE currentDate VARCHAR (15) ;-- 当前日期,有可能包含时分秒
DECLARE maxNo INT DEFAULT 0 ; -- 离现在最近的满足条件的订单编号的流水号最后5位,如:SH2013011000002的maxNo=2
-- DECLARE l_orderNo varCHAR (25) ;-- 新生成的订单编号
-- DECLARE oldDate DATE ;-- 离现在最近的满足条件的订单编号的日
DECLARE oldOrderNo VARCHAR (25) DEFAULT '' ;-- 离现在最近的满足条件的订单编号 SET @sqlcmd = concat('select * from ', tbl);
DECLARE padstrlength int DEFAULT 3;
-- DECLARE num INT DEFAULT 6 ;
-- declare orderNamePre varchar(10) DEFAULT 'PROCESS';
declare prelength INT ;
SET prelength = LENGTH(orderNamePre);
IF num = 6 THEN
SELECT DATE_FORMAT(NOW(), '%y%m%d') INTO currentDate ;-- 根据年月日生产订单编号
ELSEIF num = 8 THEN -- 根据年月日生成订单编号
SELECT DATE_FORMAT(NOW(), '%Y%m%d') INTO currentDate ;-- 订单编号形式:前缀+年月日+流水号,如:SH2013011000002
ELSEIF num = 14 THEN -- 根据年月日时分秒生成订单编号
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i%s') INTO currentDate ; -- 订单编号形式:前缀+年月日时分秒+流水号,如:SH2013011010050700001,个人不推荐使用这种方法生成流水号
ELSE -- 根据年月日时分生成订单编号
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i') INTO currentDate ;-- 订单形式:前缀+年月日时分+流水号,如:SH20130110100900005
END IF ;
-- 预处理指令的使用
SET @sqlcmd = CONCAT('SELECT IFNULL(',filed_name,', \'\') into @oldNo',
' from ', table_name,
' WHERE' ,
' SUBSTRING(',filed_name,',', prelength + 1,',',num,') = \'',currentDate,'\'',
' AND SUBSTRING(',filed_name,',1',',',prelength,') = \'',orderNamePre,'\'',
' AND LENGTH(',filed_name,') = ',prelength + padstrlength + num ,
' ORDER BY id DESC LIMIT 1 ;'
);
prepare stmt from @sqlcmd;
execute stmt;
deallocate prepare stmt;
set oldOrderNo = @oldNo;
IF oldOrderNo != '' THEN
SET maxNo = CONVERT(SUBSTRING(oldOrderNo, 0 - padstrlength),DECIMAL);-- 截取订单号后面的序列号,然后转换为DECIMAL类型变量
END IF;
SELECT CONCAT(orderNamePre,currentDate,LPAD((maxNo + 1),padstrlength,'0')) as neworderno;-- 拼接新订单号,最大订单序列号加1,如果总位数小于padstrlength,就在左边补0
end
调用:
call p('表名','订单号字段名','订单号前缀','时间类型');