MySQL实现序列(Sequence)效果

来源:互联网 发布:数字小姐是谁 知乎 编辑:程序博客网 时间:2024/06/06 07:46

由于mysql不带sequence,所以要手写的,创建一张储存sequence的表(tb_sequence),然后手动插入一条数据 ,最后自定义一个函数来处理要增长的值。

1、创建表tb_sequence,用来存放sequence值:

create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));   

2、手动插入数据:

insert into tb_sequence values('userid',100,2);  

3、定义函数 _nextval:

DELIMITER //  create function _nextval(n varchar(50)) returns integer   begin  declare _cur int;  set _cur=(select current_value from tb_sequence where name= n);  update tb_sequence   set current_value = _cur + _increment   where name=n ;  return _cur;  end;  //  

说明:delimiter // —->定义语句结束符。其他的代码 自己看吧。
4、恢复默认的语句结束符:(可以省略但是结束符必须用// ,为了方便还是设置回来。)

DELIMITER ;  

5、检验结果
多次执行以下语句:

select _nextval('userid');  

结果显示:

mysql> select _nextval('userid');  +--------------------+  | _nextval('userid') |  +--------------------+  |                102 |  +--------------------+  1 row in set (0.00 sec)  mysql> select _nextval('userid');  +--------------------+  | _nextval('userid') |  +--------------------+  |                104 |  +--------------------+  1 row in set (0.00 sec)  mysql> select _nextval('userid');  +--------------------+  | _nextval('userid') |  +--------------------+  |                106 |  +--------------------+  1 row in set (0.00 sec)  
0 0
原创粉丝点击