MySQL 新增序列三步曲

2021/12/29 19:08:17

本文主要是介绍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; //可省略



这篇关于MySQL 新增序列三步曲的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程