MySQL auto-defined sequence number: Used to do "Order No."

Source: Internet
Author: User


Auto-Define Sequence number: Used to do "Order No."

There will always be such a demand, but you may not have encountered it. Let me give an example: if the order number is generated in the form "date + serial number"

(Whether the demand is stupid or not), like this: 2015052200001234, how to deal with it?

If there is a serial number, it is better to solve. Start with 00000001, go to 99999999, then reset to a sequence, OK.


--Defining the sequence table

DROP TABLE IF EXISTS sequence;

CREATE TABLE Sequence (

Name VARCHAR (not NULL),

Current_value INT not NULL,

Increment INT not NULL DEFAULT 1,

PRIMARY KEY (name)

) Engine=innodb;

--Get the current serial number

DROP FUNCTION IF EXISTS currval;

DELIMITER $

CREATE FUNCTION Currval (seq_name VARCHAR (50))

RETURNS INTEGER

CONTAINS SQL

BEGIN

DECLARE value INTEGER;

SET value = 0;

SELECT Current_value into value

From sequence

WHERE name = Seq_name;

RETURN value;

end$

DELIMITER;

--Get the next serial number

DROP FUNCTION IF EXISTS nextval;

DELIMITER $

CREATE FUNCTION Nextval (seq_name VARCHAR (50))

RETURNS INTEGER

CONTAINS SQL

BEGIN

UPDATE sequence SET current_value = current_value + increment

WHERE name = Seq_name;

RETURN Currval (seq_name);

end$

DELIMITER;

--Reset serial number

DROP FUNCTION IF EXISTS setval;

DELIMITER $

CREATE FUNCTION Setval (Seq_name VARCHAR (), value INTEGER)

RETURNS INTEGER

CONTAINS SQL

BEGIN

UPDATE sequence SET Current_value = value

WHERE name = Seq_name;

RETURN Currval (seq_name);

end$

DELIMITER;

--Initialize data

INSERT into Sequence VALUES (' SAMPLE ', 1, 1);

--Test

SELECT currval (' SAMPLE ');

SELECT nextval (' SAMPLE ');

SELECT nextval (' SAMPLE ');

SELECT setval (' SAMPLE ', 150);

SELECT currval (' SAMPLE ');

SELECT nextval (' SAMPLE ');

SELECT nextval (' SAMPLE ');


MySQL auto-defined sequence number: Used to do "Order No."

Related Article

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.