SQL生成唯一序列号
- 建立order_seq表
CREATE TABLE IF NOT EXISTS order_seq(
timestr INT NOT NULL,
order_sn INT NOT NULL);
- 建立过程
DROP PROCEDURE IF EXISTS `seq_no`;
CREATE DEFINER = `root`@`localhost` PROCEDURE `seq_no`()
BEGIN
DECLARE v_cnt INT; /*声明变量*/
DECLARE v_timestr INT;
DECLARE rowcount BIGINT;
SET v_timestr=DATE_FORMAT(NOW(),'%Y%m%d'); /*当天日期号*/
SELECT ROUND(RAND()*100,0)+1 INTO v_cnt;/*取随机数*/
START TRANSACTION; /*启动事务*/
UPDATE order_seq SET order_sn=order_sn+v_cnt WHERE timestr=v_timestr;/*再前面数据基础上累加,不会出现重复单号*/
IF ROW_COUNT()=0 THEN
INSERT INTO order_seq(timestr,order_sn) VALUES(v_timestr,v_cnt);
END IF;/*行数为0插入数据*/
SELECT CONCAT(v_timestr,LPAD(order_sn,7,0)) AS order_sn /*日期与随机数拼接*/
FROM order_seq WHERE timestr=v_timestr;
COMMIT;
END;