1建立表
create table `tb_sequence` (
`seq_name` varchar(50) not null comment '欄位名稱',
`min` int(11) not null comment '最小值',
`max` int(11) not null comment '最大值',
`current_val` int(11) not null comment '當前',
`increment_val` int(11) not null default '1' comment '步長',
`remark` varchar(50) default null comment '備註',
primary key (`seq_name`)
) engine=innodb default charset=utf8;
2建立自增函式
create definer=`root`@`%` function `_nextval`(name varchar(50)) returns int(11)
begin
declare _cur int;
declare _maxvalue int;
declare _increment int;
set _increment = (select increment_val from tb_sequence where seq_name = name);
set _maxvalue = (select max from tb_sequence where seq_name = name);
set _cur = (select current_val from tb_sequence where seq_name = name);
update tb_sequence
set current_val = _cur + increment_val
where seq_name = name ;
return _cur;
end3.取值
select right(1000000+_nextval(seq_name),6) from dual
可以補全6位
建表語句中修改為myisam改為了innodb,因為5.6中myisam不支援事務
MySQL 之自己實現sequence
oracle的sequence是乙個很好的主鍵生成策略,但是mysql並不具有sequence語法,下面在mysql中來模擬實現乙個sequence。1 建一張表e sys sequence用來記錄序列名稱和值 drop table ifexists e sys sequence create ta...
MySQL實現序列(Sequence)效果
mysql實現序列效果 一般使用序列 sequence 來處理主鍵字段,在mysql中是沒有序列的,但是mysql有提供了自增長 increment 來實現類似的目的,但也只是自增,而不能設定步長 開始索引 是否迴圈等,最重要的是一張表只能由乙個字段使用自增,但有的時候我們需要兩個或兩個以上的字段實...
MySQL 實現自增函式sequence
當前資料庫為 mysql 由於mysql和oracle不太一樣,不支援直接的sequence,所以需要建立一張table來模擬sequence的功能,理由sql語句如下 create table sequence name varchar 50 collate utf8 bin not null c...