第一步:创建一个索引管理表,其中包含,索引名称、最小值、最大值、当前值、增量,并设置主键为索引名称。

CREATE TABLE TB_SEQUENCE (
    SEQ_NAME VARCHAR(50) NOT NULL,
    MINVALUE INT NOT NULL ,
    MAX_VAL DECIMAL(31) NOT NULL,
    CURRENT_VAL DECIMAL(31) NOT NULL,
    INCREMENT_VAL INT DEFAULT '1' NOT NULL,
    PRIMARY KEY (SEQ_NAME)
)

 

第二步:给索引管理表中插入要实现的一条索引管理数据

INSERT INTO TB_SEQUENCE (SEQ_NAME, MINVALUE, MAX_VAL, CURRENT_VAL, INCREMENT_VAL) values ('SEQ_NUM', 1,  9999999999999999999999999999999, 1, 1);

 

第三步:创建一个获取下一条数据的函数

DELIMITER $$
create function _nextval(name varchar(50)) returns DECIMAL(31)   
begin  
declare _cur DECIMAL(31);
declare _maxvalue DECIMAL(31);
declare _increment int;
declare _nextVal DECIMAL(31);
set _cur = (select CURRENT_VAL from TB_SEQUENCE where SEQ_NAME = name);  
set _increment = (select INCREMENT_VAL from TB_SEQUENCE where SEQ_NAME = name);
set _maxvalue = (select MAX_VAL from TB_SEQUENCE where SEQ_NAME = name);
set _nextVal = _cur + _increment;
update TB_SEQUENCE set CURRENT_VAL = _nextVal where SEQ_NAME = name ;
if(_nextVal >= _maxvalue) then
    update TB_SEQUENCE set CURRENT_VAL = 1 where SEQ_NAME = name ;
end if;
return _nextVal;
end; 
$$
DELIMITER ;

 

好了~

测试一下:

select _nextval('SEQ_NUM') from dual;

 

 点个赞吧,鼓励一下!