在MySQL中创建实现自增的序列(Sequence)

首先创建--Sequence 管理表

-- ----------------------------
-- Table structure for dl_sequence
-- ----------------------------
DROP TABLE IF EXISTS `dl_sequence`;
CREATE TABLE `dl_sequence`  (
  `seq_name` varchar(50) COLLATE UTF8_BIN NOT NULL COMMENT '序列的名称',
  `current_value` int(11)  NOT NULL COMMENT '序列当前值',
  `increment` int(11)  NOT NULL COMMENT '序列自增值',
  primary key (`seq_name`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = UTF8_BIN COMMENT = '自增序列表' ROW_FORMAT = Compact;

   1   创建--取当前值的函数

DROP FUNCTION IF EXISTS currval;
DELIMITER $
CREATE FUNCTION currval (seq_name_val VARCHAR(30))
      RETURNS INTEGER
      LANGUAGE SQL
      DETERMINISTIC
      CONTAINS SQL
      SQL SECURITY DEFINER
      COMMENT '获取序列当前值'
BEGIN
      DECLARE value INTEGER;
      SET value = 0;
      SELECT current_value INTO value FROM dl_sequence where seq_name = seq_name_val;
      RETURN value;
END
$
DELIMITER ;

2 创建--取下一个值的函数

DROP FUNCTION IF EXISTS nextval;
DELIMITER $
CREATE FUNCTION nextval (seq_name_val VARCHAR(30))
      RETURNS INTEGER
      LANGUAGE SQL
      DETERMINISTIC
      CONTAINS SQL
      SQL SECURITY DEFINER
      COMMENT '获取下一个序列值'
BEGIN
      UPDATE dl_sequence SET current_value = current_value + increment where seq_name = seq_name_val;
      RETURN currval(seq_name_val);
END
$
DELIMITER ;

3创建--更新当前值的函数

DROP FUNCTION IF EXISTS setval;
DELIMITER $
CREATE FUNCTION setval (seq_name_val VARCHAR(30), curr_val INTEGER)
      RETURNS INTEGER
      LANGUAGE SQL
      DETERMINISTIC
      CONTAINS SQL
      SQL SECURITY DEFINER
      COMMENT '更新当前值'
BEGIN
      UPDATE dl_sequence SET current_value = curr_val where seq_name = seq_name_val;
      RETURN currval(seq_name_val);
END
$
DELIMITER ;
 

4测试

-- insert into dl_sequence values('test',1,1);
select currval('test');
select nextval('test');
select setval('test',10);

你可能感兴趣的:(db,db,mysql)