mysql 实现 序列

创建序列表:

CREATE TABLE SEQUENCE ( NAME VARCHAR(50) NOT NULL, CURRENT_VALUE BIGINT NOT NULL, STEP INT NOT NULL DEFAULT 1, PRIMARY KEY (NAME) ) ENGINE=INNODB; 

插入序列测试

insert into SEQUENCE values(‘SEQ_TEST‘,1,1);

添加获取序列当前值函数:

DROP FUNCTION IF EXISTS currval;
DELIMITER $
CREATE FUNCTION currval (seq_name VARCHAR(30))
RETURNS INTEGER
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ‘‘
BEGIN
DECLARE VALUE INTEGER;
SET VALUE = 0;
SELECT CURRENT_VALUE INTO VALUE
FROM SEQUENCE
WHERE NAME = seq_name;
RETURN VALUE;
END
$
DELIMITER ;

添加获取序列下一个值函数:

DROP FUNCTION IF EXISTS nextval;
DELIMITER $
CREATE FUNCTION nextval (seq_name VARCHAR(50))
RETURNS INTEGER
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ‘‘
BEGIN
UPDATE SEQUENCE
SET CURRENT_VALUE = CURRENT_VALUE + STEP
WHERE NAME = seq_name;
RETURN currval(seq_name);
END
$
DELIMITER ;

测试:


SELECT currval(‘SEQ_TEST‘);
SELECT nextval(‘SEQ_TEST‘);

相关推荐