oracle函数
bitscn.com mysql中实现类似oracle中的nextval函数
我们知道mysql中是不支持sequence的,一般是建表的时间使这个字段自增。
如 create table table_name(id int auto_increment primary key, ...);
或者alter table table_ame add id int auto_increment primary key //字段,一定设置为primary key
或者重设自增字段的起步值 alter table table_name auto_increment=n
但是我们在oracle中经常使用sequence_name.nextval,或者在程序中我们使用先select sequence_name.value from dual.如果我们的开发框架要同时支持oracle和mysql。一般会把取sequence提出来。如果在mysql中提供一个类似的函数,这样提出来会比较方便些。这是一种使用的场景。下面就说说怎么在mysql中实现一个nextval函数吧。
1先建一表
sql代码
create table `sys_sequence` (
`name` varchar(50) not null,
`current_value` int(11) not null default '0',
`increment` int(11) not null default '1',
primary key (`name`)
)
2.然后建立函数
sql代码
delimiter $$
drop function if exists `currval`$$
create definer=`root`@`%` function `currval`(seq_name varchar(50)) returns int(11)
begin
declare value integer;
set value=0;
select current_value into value
from sys_sequence
where name=seq_name;
return value;
end$$
delimiter ;
create definer=`root`@`%` function `nextval`(seq_name varchar(50)) returns int(11)
begin
update sys_sequence
set current_value = current_value + increment
where name=seq_name;
return currval(seq_name);
end
create definer=`root`@`%` function `setval`(seq_name varchar(50),value integer) returns int(11)
begin
update sys_sequence
set current_value=value
where name=seq_name;
return currval(seq_name);
end
?
测试下 select nextval('name') ; 搞定。
bitscn.com