Mysql implements functions like nextval in oracle _ MySQL

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.