Implement nextval functions in mysql similar to those in oracle

Source: Internet
Author: User

Mysql implements functions similar to nextval in oracle. We know that sequence is not supported in mysql. Generally, this field is auto-incrementing by the table creation time. Www.2cto.com such as create table table_name (id int auto_increment primary key ,...); or alter table table_ame add id int auto_increment primary key // field, it 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 in the program, we use select sequence_name.value from dual. 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. Create table 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. then CREATE the FUNCTION www.2cto.com 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; SEL ECT 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.
 

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.