-- 创建序列表
-- 防止误删序列表将下面这条语句注释
-- drop table if exists sequence;
create table sequence ( name varchar(50) not null, current_value bigint not null, increment int not null default 1, primary key (name)) engine = innodb;
-- 创建函数 - 获取当前序列值
drop function if exists currval;
delimiter $$
create function currval(seq_name varchar (50)) returns bigint
begin
declare value bigint;
set value = -1;
select current_value into value from sequence where name = seq_name;
return value;
end $$
delimiter ;
-- 创建函数 - 获取下一序列值 last_insert_id()函数完成并发控制
drop function if exists nextval;
delimiter $$
create function nextval(seq_name varchar (50)) returns bigint
begin
update sequence set current_value=last_insert_id(current_value + increment) where name = seq_name;
-- 此if用于处理序列不存在时的返回值,因为当序列不存在时,update不执行,last_insert_id()的值不能确定
-- 如果有动态创建序列的需求,可根据返回值为0判断序列不存在
return if(row_count()=0,0,last_insert_id());end $$
delimiter ;
-- 创建函数 - 重置当前序列值
drop function if exists resetval;
delimiter $$
create function resetval(seq_name varchar (50),value bigint) returns bigint
begin
update sequence set current_value = value where name = seq_name;
return currval ( seq_name );
end $$
delimiter ;
-- 添加序列
insert into sequence values( 'SEQ_YWBH',0,1);
-- 查询序列当前值
select currval('SEQ_YWBH');
-- 查询序列下一值
select nextval('SEQ_YWBH');
-- 重置序列当前值
select resetval('SEQ_YWBH',0);
Mysql序列使用
最新推荐文章于 2023-06-21 17:33:06 发布