MySql实现序列

1、创建序列表

 

CREATE TABLE IF NOT EXISTS `sequence` (

`name` VARCHAR ( 50 ) NOT NULL,

`current_value` INT ( 11 ) NOT NULL,

`increment` INT ( 11 ) NOT NULL DEFAULT '1'

)

ENGINE = InnoDB 

DEFAULT CHARSET = utf8

CHECKSUM = 1

DELAY_KEY_WRITE = 1

ROW_FORMAT = DYNAMIC

COMMENT = '序列表';

 

2、创建序列函数

 

2.1、清除同名函数(不推荐直接使用)

DROP FUNCTION IF EXISTS `currval`;

 

2.2、新建函数(获取当前值)

CREATE FUNCTION `currval` ( seq_name VARCHAR ( 50 ) ) RETURNS INT ( 11 ) READS SQL DATA DETERMINISTIC

BEGIN

DECLARE VALUE INTEGER;

SET VALUE = 0;

SELECT current_value INTO VALUE FROM sequence WHERE NAME = seq_name;

RETURN VALUE;

END

 

2.3、清除同名函数(不推荐直接使用)

DROP FUNCTION IF EXISTS `nextval`;

 

2.4、新建函数(获取下一个值)

CREATE FUNCTION `nextval` ( seq_name VARCHAR ( 50 ) ) RETURNS INT ( 11 ) DETERMINISTIC

BEGIN

UPDATE sequence SET current_value = current_value + increment WHERE NAME = seq_name;

RETURN currval ( seq_name );

END

 

3、创建序列

INSERT INTO `sequence` ( `name`, `current_value`, `increment` ) VALUES ( 'seq_buz_tender_info', 0, 1 );

INSERT INTO `sequence` ( `name`, `current_value`, `increment` ) VALUES ( 'seq_buz_engineering_task', 0, 1 );

 

4、调用

SELECT currval( "seq_buz_tender_info" );

SELECT nextval ( "seq_buz_tender_info" );

 

SELECT currval( "seq_buz_engineering_task" );

SELECT nextval ( "seq_buz_engineering_task" );

 

SELECT CONCAT('1','2019','1',LPAD((select fx_nextval('seq_buz_engineering_task')),4,0))

 

5、说明

(Linux)执行2.22.4时,可能出现异常【1419 - You do not have the SUPER privilege and binary logging is enabled】,解决办法如下:

第一步,用root用户登录:

mysql -u root -p

(输入密码)

第二步,设置参数log_bin_trust_function_creators为1:

set global log_bin_trust_function_creators = 1;

你可能感兴趣的:(数据库技术)