怎么给MySQL增加Sequence管理功能

本篇内容介绍了“怎么给MySQL增加Sequence管理功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联建站主要从事网站设计、成都网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务银海,10多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220

-- 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)
) ENGINE=InnoDB;
 
-- 取当前值的函数
DROP FUNCTION IF EXISTS currval;
DELIMITER $
CREATE FUNCTION currval (seq_name VARCHAR(50))
         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 + increment
                   WHERE name = seq_name;
         RETURN currval(seq_name);
END
$
DELIMITER ;
 
-- 更新当前值的函数
DROP FUNCTION IF EXISTS setval;
DELIMITER $
CREATE FUNCTION setval (seq_name VARCHAR(50), value INTEGER)
         RETURNS INTEGER
         LANGUAGE SQL
         DETERMINISTIC
         CONTAINS SQL
         SQL SECURITY DEFINER
         COMMENT ''
BEGIN
         UPDATE sequence
                   SET current_value = value
                   WHERE name = seq_name;
         RETURN currval(seq_name);
END
$
DELIMITER ;
 
/*
-- 测试
INSERT INTO sequence VALUES ('TestSeq', 0, 1);
SELECT SETVAL('TestSeq', 10);
SELECT CURRVAL('TestSeq');
SELECT NEXTVAL('TestSeq');
*/

“怎么给MySQL增加Sequence管理功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


当前名称:怎么给MySQL增加Sequence管理功能
转载源于:http://myzitong.com/article/jdjedd.html