mysql 如何设置自动增长序列 sequence(一)

来源:互联网 发布:ecshop3源码下载 编辑:程序博客网 时间:2024/05/19 18:46

http://blog.csdn.net/codinghome/article/details/7598032




背景:由于项目需要,必须用mysql设置主键自增长,而且想用字符串的。经过上网查找并且实验,终于做出了一套方案。现在就共享给大家!


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


一起做吧:

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

 

[sql] view plaincopyprint?
  1. create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));   

2、手动插入数据:
[sql] view plaincopyprint?
  1. insert into tb_sequence values('userid',100,2);  

3、定义函数 _nextval:
[sql] view plaincopyprint?
  1. DELIMITER //  
  2. create function _nextval(n varchar(50)) returns integer   
  3. begin  
  4. declare _cur int;  
  5. set _cur=(select current_value from tb_sequence where name= n);  
  6. update tb_sequence  
  7.  set current_value = _cur + _increment  
  8.  where name=n ;  
  9. return _cur;  
  10. end;  
  11. //  

说明:delimiter //   ---->定义语句结束符。其他的代码 自己看吧。

4、恢复默认的语句结束符:(可以省略但是结束符必须用// ,为了方便还是设置回来。)

[sql] view plaincopyprint?
  1. DELIMITER ;  

5、检验结果 

多次执行以下语句:

[sql] view plaincopyprint?
  1. select _nextval('userid');  

结果显示:
[sql] view plaincopyprint?
  1. mysql> select _nextval('userid');  
  2. +--------------------+  
  3. | _nextval('userid') |  
  4. +--------------------+  
  5. |                102 |  
  6. +--------------------+  
  7. 1 row in set (0.00 sec)  
  8.   
  9. mysql> select _nextval('userid');  
  10. +--------------------+  
  11. | _nextval('userid') |  
  12. +--------------------+  
  13. |                104 |  
  14. +--------------------+  
  15. 1 row in set (0.00 sec)  
  16.   
  17. mysql> select _nextval('userid');  
  18. +--------------------+  
  19. | _nextval('userid') |  
  20. +--------------------+  
  21. |                106 |  
  22. +--------------------+  
  23. 1 row in set (0.00 sec)  

6、实验结束。
0 0
原创粉丝点击