ITPub博客

首页 > 数据库 > MySQL > MySql序列实现

MySql序列实现

原创 MySQL 作者:呆呆笨笨的鱼 时间:2014-11-04 17:48:09 0 删除 编辑
小结一下:mysql 实现 oracle中序列的功能

创建一张用于记录序列值的表:

drop table if exists dpf_risk.seq_record;
create table dpf_risk.seq_record
(
seq_name varchar(100) comment '序列名'
,val int(11) not null default 0 comment '序列值'
,primary key (seq_name)
) comment '此表用于记录序列的值'
;
/*初始化序列的其实值:insert into dpf_risk.seq_record(seq_name,val) values('rdm_lkp_uid_rid_mobile_emal_uid',989719);
update dpf_risk.seq_record 
set val = 989719
*/

创建取序列值的函数 (此为 next_val()的实现,current_val()同理,步长可以自己定义,很方便)
drop function if exists dpf_risk.seq; 
DELIMITER $$
create function dpf_risk.seq(seq_name varchar(100)) returns int(11) 
not DETERMINISTIC
begin 
 declare res int default 0;
 update dpf_risk.seq_record set val = last_insert_id(val+1) where seq_name = seq_name ;  
 
 select last_insert_id(val) into res from dpf_risk.seq_record where seq_name = seq_name ;  
 
 return res;  
end$$
DELIMITER ;

测试一下:

mysql> select dpf_risk.seq('rdm_lkp_uid_rid_mobile_emal_uid');
+-------------------------------------------------+
| dpf_risk.seq('rdm_lkp_uid_rid_mobile_emal_uid') |
+-------------------------------------------------+
|                                          989721 |
+-------------------------------------------------+
1 row in set (0.00 sec)


mysql> select dpf_risk.seq('rdm_lkp_uid_rid_mobile_emal_uid');
+-------------------------------------------------+
| dpf_risk.seq('rdm_lkp_uid_rid_mobile_emal_uid') |
+-------------------------------------------------+
|                                          989722 |
+-------------------------------------------------+
1 row in set (0.00 sec)


功能实现!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28929558/viewspace-1320370/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-04-17

  • 博文量
    62
  • 访问量
    939480