mysql数据库给表创建序列

来源:互联网 发布:unity3d 5.3.4f1 下载 编辑:程序博客网 时间:2024/06/07 07:18
今天自己在玩项目时,发现自己没有弄过序列,以前只是用过,今天一用才发现,还是有点学问的:
mysql和oracle数据库创建索引还是不一样的
oracle数据库自带创建索引功能,某些特定客户端可以直接使用工具创建索引,很简单,在这里就不细说了
但是mysql创建索引就需要一步一步写sql来执行了,话不多说,一步一步的流程如下,博主亲测。

mysql数据库给表创建序列

第一步:创建--Sequence 管理表
drop table if exists sequence;
create table sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name)); 
第二步:创建某条具体索引
(三个参数为 索引名,启示值,自增值)
insert into sequence values('seq_opt_log',1000000,1);

第三步:创建--取下一个值的函数
DROP FUNCTION IF EXISTS `nextval`;
create function nextval(n varchar(50)) returns integer
begin
declare _cur int;
set _cur=(select current_value from sequence where name= n);
update sequence
set current_value = _cur + _increment
where name=n ;
return _cur;
end;
第四步:获取序列值
(seq_opt_log为第二步中所设置具体索引名)
select nextval('seq_opt_log');
完结。
使用时直接执行SQL:select nextval('seq_opt_log'); 即可

在这里面,每个创建table和创建function之前我都drop一下是为了防止在该数据库在建这个table之前或者function之前已经有相应对象,这也是写
DDL语言应该具备的良好习惯。
原创粉丝点击