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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章