原文转载地址
http://blog.csdn.net/dengsilinming/article/details/8488626#insertcode
mysql版本说明:mysql5.5
原文中sql语句报错,下面是测验通过的。
DELIMITER //
CREATE PROCEDURE `generate_orderNo`(in orderNamePre char(2), in num int, out newOrderNo varchar(25))
BEGIN
DECLARE currentDate varCHAR (15) ;
DECLARE maxNo INT DEFAULT 0 ;
DECLARE oldOrderNo VARCHAR (25) DEFAULT '' ;
if num = 8 then
SELECT DATE_FORMAT(NOW(), '%Y%m%d') INTO currentDate ;
elseif num = 14 then
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i%s') INTO currentDate ;
else
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i') INTO currentDate ;
end if ;
SELECT IFNULL(orderNo, '') INTO oldOrderNo
FROM test_orders
WHERE SUBSTRING(orderNo, 3, num) = currentDate
AND SUBSTRING(orderNo, 1, 2) = orderNamePre
and length(orderNo) = 7 + num
ORDER BY id DESC LIMIT 1 ;
IF oldOrderNo != '' THEN
SET maxNo = CONVERT(SUBSTRING(oldOrderNo, -5), DECIMAL) ;
END IF ;
SELECT
CONCAT(orderNamePre, currentDate, LPAD((maxNo + 1), 5, '0')) INTO newOrderNo ;
SELECT
newOrderNo ;
END
补充网友使用过程中提出的问题,具体内容如下:
1. 测试语句不好使,故重新调整为(按顺序执行):
CALL `generate_orderNo`('SH', 12, @orderNo);
INSERT INTO test_orders (orderNo, orderName) VALUES(@orderNo, '测试订单');
2. 新需求:“不加前缀,随机流水号为3位”,代码如下:
DELIMITER //
CREATE PROCEDURE `generate_orderNo`(in num int, out newOrderNo varchar(25))
BEGIN
DECLARE currentDate varCHAR (15) ;
DECLARE maxNo INT DEFAULT 0 ;
DECLARE oldOrderNo VARCHAR (25) DEFAULT '' ;
if num = 8 then
SELECT DATE_FORMAT(NOW(), '%Y%m%d') INTO currentDate ;
elseif num = 14 then
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i%s') INTO currentDate ;
else
SELECT DATE_FORMAT(NOW(), '%Y%m%d%H%i') INTO currentDate ;
end if ;
SELECT IFNULL(orderNo, '') INTO oldOrderNo
FROM test_orders
WHERE SUBSTRING(orderNo, 1, num) = currentDate
and length(orderNo) = 3 + num
ORDER BY id DESC LIMIT 1 ;
IF oldOrderNo != '' THEN
SET maxNo = CONVERT(SUBSTRING(oldOrderNo, -3), DECIMAL) ;
END IF ;
SELECT
CONCAT(currentDate, LPAD((maxNo + 1),3, '0')) INTO newOrderNo ;
SELECT
newOrderNo ;
end