先建一表
DROP TABLE IF EXISTS `sys_sequence`;CREATE TABLE `sys_sequence` ( `key` varchar(40) NOT NULL DEFAULT '', `value` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`key`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO sys_sequence(`key`,`value`) VALUES('increment', 1);
然后建立函数 currval/1
set global log_bin_trust_function_creators = 1;DELIMITER $$DROP FUNCTION IF EXISTS `currval`$$CREATE DEFINER=`root`@`%` FUNCTION `currval`(seq_name VARCHAR(40)) RETURNS INT(11)BEGINDECLARE ret_value INTEGER;SET ret_value=0;SELECT `value` INTO ret_valueFROM sys_sequenceWHERE `key`=seq_name;RETURN ret_value;END$$DELIMITER ;
执行函数
select currval('increment');
创建函数nextval/2
DELIMITER $$DROP FUNCTION IF EXISTS `nextval`$$CREATE DEFINER=`root`@`%` FUNCTION `nextval`(seq_name varchar(40), incr int(11)) RETURNS int(11)BEGINUPDATE `sys_sequence`SET `value` = `value` + incrwhere `key`=seq_name;return currval(seq_name);END$$
执行函数
select nextval('increment', 2);