-- 创建过程和表
DROP TABLE IF EXISTS test_orders;
CREATE TABLE `test_orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_no` varchar(25) NOT NULL DEFAULT '',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8;
DROP PROCEDURE IF EXISTS generate_orderNo;
CREATE PROCEDURE `generate_orderNo`(in orderNamePre char(2),out newOrderNo varchar(25))
BEGIN
DECLARE currentDate VARCHAR (15) ;-- 当前日期,有可能包含时分秒
DECLARE maxNo INT DEFAULT 0 ; -- 离现在最近的满足条件的订单编号的流水号最后5位,如:SH2013011000002的maxNo=2
DECLARE oldOrderNo VARCHAR (25) DEFAULT '' ;-- 离现在最近的满足条件的订单编号
SELECT DATE_FORMAT(NOW(), '%Y%m%d') INTO currentDate ;-- 订单编号形式:前缀+年月日+流水号,如:SH2013011000002
SELECT IFNULL(order_no, '') INTO oldOrderNo
FROM test_orders
WHERE SUBSTRING(order_no, 3, 8) = currentDate
AND SUBSTRING(order_no, 1, 2) = orderNamePre
and length(order_no) = 13
ORDER BY id DESC LIMIT 1 ; -- 有多条时只显示离现在最近的一条
IF oldOrderNo != '' THEN
SET maxNo = CONVERT(SUBSTRING(oldOrderNo, -3), DECIMAL) ;-- SUBSTRING(oldOrderNo, -5):订单编号如果不为‘‘截取订单的最后5位
END IF ;
SELECT
CONCAT(orderNamePre, currentDate, LPAD((maxNo + 1), 3, '0')) INTO newOrderNo ; -- LPAD((maxNo + 1), 5, '0'):如果不足5位,将用0填充左边
INSERT INTO test_orders (order_no) VALUES (newOrderNo) ; -- 向订单表中插入数据
SELECT
newOrderNo ;
END;
-- navicat中获取流程号
SET @orderNo = '';
CALL `generate_orderNo`('PD', @orderNo);
SELECT @orderNo;
-- java 代码实现
@GetMapping()
public String getNo(){
Map map = new HashMap<String,String>();
map.put("preFix","PD");
map.put("orderNo","");
myService.getOrderNo(map);
System.out.println(map);
System.out.println(map.get("orderNo"));
return null;
}
@Select("call generate_orderNo(#{map.preFix,mode=IN,jdbcType=VARCHAR},#{map.orderNo,mode=OUT,jdbcType=VARCHAR})")
@Options(statementType=StatementType.CALLABLE)
String callProcedure(@Param("map")Map map);