zoukankan      html  css  js  c++  java
  • 给MySQL增加Sequence管理功能

    -- 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');
    */
  • 相关阅读:
    C#中的Virtual
    DevExpress控件中LayoutControl的使用
    汉字获取首字母拼音
    工具类
    C# 根据时间创建文件夹
    图片延迟加载
    IIS日志分析的作用
    SQL2008R2 无法读取此系统上以前注册的服务器的列表--网上方法不可行
    windows 服务器系统日志分析及安全
    301跳转
  • 原文地址:https://www.cnblogs.com/smile361/p/3082182.html
Copyright © 2011-2022 走看看