程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> 給MySQL增加Sequence管理功能

給MySQL增加Sequence管理功能

編輯:MySQL綜合教程

-- 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');
*/

作者 json的博客

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved