mysql实现自增序列的示例代码
程序员文章站
2022-09-21 12:46:32
1.创建sequence表create table `sequence` ( `name` varchar(50) collate utf8_bin not null comment '序列的名字',...
1.创建sequence表
create table `sequence` ( `name` varchar(50) collate utf8_bin not null comment '序列的名字', `current_value` int(11) not null comment '序列的当前值', `increment` int(11) not null default '1' comment '序列的自增值', primary key (`name`) ) engine=innodb default charset=utf8 collate=utf8_bin;
2.创建–取当前值的函数
drop function if exists currval; delimiter $ create function currval (seq_name varchar(50)) returns integer language sql deterministic contains sql sql security definer comment '' begin declare value integer; set value = 0; select current_value into value from sequence where name = seq_name; return value; end $ delimiter ;
3.创建–取下一个值的函数
drop function if exists nextval; delimiter $ create function nextval (seq_name varchar(50)) returns integer language sql deterministic contains sql sql security definer comment '' begin update sequence set current_value = current_value + increment where name = seq_name; return currval(seq_name); end $ delimiter ;
4.创建–更新当前值的函数
drop function if exists setval; delimiter $ create function setval (seq_name varchar(50), value integer) returns integer language sql deterministic contains sql sql security definer comment '' begin update sequence set current_value = value where name = seq_name; return currval(seq_name); end $ delimiter ;
5.测试添加实例 执行sql
insert into sequence values ('testseq', 0, 1);-- 添加一个sequence名称和初始值,以及自增幅度 select setval('testseq', 10);-- 设置指定sequence的初始值 select currval('testseq');-- 查询指定sequence的当前值 select nextval('testseq');-- 查询指定sequence的下一个值
到此这篇关于mysql实现自增序列的示例代码的文章就介绍到这了,更多相关mysql 自增序列内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读