Implementation of functions similar to nextval in oracle in mysql
BitsCN.com
Implement nextval functions in mysql similar to those in oracle
We know that sequence is not supported in mysql. Generally, this field is auto-incrementing by the time the table is created.
For example, create table table_name (id int auto_increment primary key ,...);
Or alter table table_ame add id int auto_increment primary key // the field must be set to primary key.
Or reset the starting value of the auto-increment field. alter table table_name AUTO_INCREMENT = n
However, sequence_name.nextval is often used in oracle, or select sequence_name.value from dual in the program. if our development framework must support both oracle and mysql. We generally propose sequence. If a similar function is provided in mysql, it is more convenient to propose it. This is an application scenario. The following describes how to implement a nextval function in mysql.
1. create a table first
SQL code
Create table 'sys _ sequence '(
'Name' varchar (50) not null,
'Current _ value' int (11) not null default '0 ',
'Credentials' int (11) not null default '1 ',
Primary key ('name ')
)
2. create a function
SQL code
DELIMITER $
Drop function if exists 'currval' $
Create definer = 'root' @ '%' FUNCTION 'currval' (seq_name VARCHAR (50) returns int (11)
BEGIN
Declare value integer;
Set value = 0;
SELECT current_value INTO VALUE
FROM sys_sequence
Where name = seq_name;
Return value;
END $
DELIMITER;
Create definer = 'root' @ '%' FUNCTION 'nextval' (seq_name varchar (50) RETURNS int (11)
BEGIN
UPDATE sys_sequence
SET CURRENT_VALUE = CURRENT_VALUE + INCREMENT
Where name = seq_name;
Return currval (seq_name );
END
Create definer = 'root' @ '%' FUNCTION 'setval '(seq_name varchar (50), value integer) RETURNS int (11)
BEGIN
Update sys_sequence
Set current_value = value
Where name = seq_name;
Return currval (seq_name );
END
?
Test select nextval ('name.
BitsCN.com