数据库
首页 > 数据库> > MySQL 新增序列三步曲

MySQL 新增序列三步曲

作者:互联网

 

1、创建一个统一管理序列的表sequences

drop table if exists sequences;
create table sequences
(
  SEQUENCE_NAME varchar(80)  not null comment '自增序列名称'
    primary key,
  INCREMENT_BY  int          not null comment '步长',
  CURRENT_VALUE bigint       not null comment '当前值',
  MIN_VALUE     bigint       null comment '最小值',
  MAX_VALUE     bigint       null comment '最大值',
  COMMENTS      varchar(200) null comment '序列描述',
  CYCLE         varchar(10)  null comment '当值为CYCLE时,代表循环'
);

2、创建一个自增序列函数

drop function if exists nextval;
create function nextval(a_seq_name varchar(55))
  returns bigint
  BEGIN
    DECLARE seq_val BIGINT;
    DECLARE min_val BIGINT;
    DECLARE max_val BIGINT;
    DECLARE cycle_val VARCHAR(10);
    SET seq_val = -1;
    IF EXISTS(SELECT 1
              FROM sequences holdlock
              WHERE SEQUENCE_NAME = a_seq_name)
    THEN
      SELECT
        CURRENT_VALUE + INCREMENT_BY,
        MIN_VALUE,
        MAX_VALUE,
        CYCLE
      INTO seq_val, min_val, max_val, cycle_val
      FROM sequences
      WHERE SEQUENCE_NAME = a_seq_name FOR UPDATE;
      IF seq_val > max_val
      THEN
        IF cycle_val = 'CYCLE'
        THEN
          SET seq_val = min_val;
        ELSE
          SIGNAL SQLSTATE '42000'
          SET MESSAGE_TEXT ='error:1000,sequence beyond the max value ';
        END IF;
      END IF;
      UPDATE sequences
      SET CURRENT_VALUE = seq_val
      WHERE SEQUENCE_NAME = a_seq_name;
    ELSE
      SIGNAL SQLSTATE '42000'
      SET MESSAGE_TEXT ='error:1001,Query was empty,sequence name not found ';
    END IF;
    RETURN seq_val;
  END;

3、插入数据

insert into sequences(sequence_name, increment_by, current_value, min_value, max_value, comments, cycle)
value ('PHONE_NBR_SEQ', 1, 20221001, 20221001, 9999999999, '手机号码序列', null);

4、查询序列

select nextval('PHONE_NBR_SEQ')
from dual; //可省略

标签:comment,val,seq,sequences,VALUE,MySQL,序列,null,三步
来源: https://www.cnblogs.com/passex/p/15745993.html