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值:
- 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)
6、实验结束。
0 0
- mysql 如何设置自动增长序列 sequence(一)
- mysql 如何设置自动增长序列 sequence(一)
- mysql 如何设置自动增长序列 sequence(一)
- mysql 如何设置自动增长序列 sequence(一)
- mysql 如何设置自动增长序列 sequence(一)
- MySQL如何设置自动增长序列 SEQUENCE
- mysql 如何设置自动增长序列 sequence(二) 在实际中调用
- mysql 如何设置自动增长序列 sequence(二) 在实际中调用
- mysql 如何设置自动增长序列 sequence(二) 在实际中调用
- oracle如何设置序列自动增长
- MySQL如何设置自动增长列
- 设置mysql自动增长
- Oracle自动增长序列介绍——sequence
- mysql自动增长字段的设置
- mysql,sqlserver,oracle主键自动增长设置
- mysql 自动增长起始值设置
- 设置mysql中自动增长的初始值
- 笔记2-MySQL设置自动增长
- (NO.00001)iOS游戏SpeedBoy Lite成形记(一)
- 【MySQL】【leetcode】 Customers Who Never Order解题报告
- for what? so what?
- 基本C++概念
- jQuery搜索子元素的方法教程
- mysql 如何设置自动增长序列 sequence(一)
- qemu-2.4.0编译时出错:error: ‘XFS_IOC_ZERO_RANGE’ undeclared (first use in this function)
- c# XML和实体类之间相互转换(序列化和反序列化)
- Linux双网卡:一个配置外网,一个配置内网
- Windows与Linux程序的返回值
- C#内存优化
- WARN TaskSchedulerImpl: Initial job has not accepted any resources; check your cluster uito ensure
- js 页面数字倒计时
- 开源大数据处理工具汇总(下)