Mysql序列使用

-- 创建序列表
-- 防止误删序列表将下面这条语句注释
-- 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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值