Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Increment including Year and Month in MySql

Tags:

java

mysql

I have a table called > Project with an auto increment field for project estimate bid number called Project_ID.

This field is auto incremented. I have created it as an 8 digit character field which carries the field rule.

I need it to auto increment as a two number year, two number month, include a hyphen, and then a number starting at 001 for first record in that time period.

An example for the month of April 2012 would be 1204-001 for the first record, 1204-002 for the 2nd and etc. then when the month of May rolls around the Project_ID would change to 1205-001.

What I’ve been trying to write is as follows, I kept it as a simple default expression with a default value of

Cyear(date()) + (month()) + “-“ + “001” . 

How I have Achieve this?

like image 281
MadTech Avatar asked Feb 12 '13 08:02

MadTech


People also ask

Can we have 2 auto increment in MySQL?

You can't have two auto-increment columns.

Can we insert auto increment value in MySQL?

Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How does auto increment in MySQL works?

Auto Increment is a function that operates on numeric data types. It automatically generates sequential numeric values every time that a record is inserted into a table for a field defined as auto increment.

Why is my auto increment not working in MySQL?

Basically this is a bug in MySQL that causes the problem but a work around is simple. The problem happens when the Auto-Increment value of a table grows beyond the limit. Just run this SQL query in MySQL to fix the bug.


1 Answers

Basically, you can use BEFORE INSERT TRIGGER on the table you want the column to be incremented.

Here are some steps to create a simple algorithm and put this code inside the trigger:

// get current YEAR
SET @cur_Year = CONCAT(DATE_FORMAT(CURDATE(), '%Y'));
// get current MONTH
SET @cur_MONTH = CONCAT(DATE_FORMAT(CURDATE(), '%m'));
// concatenate YEAR and MONTH
SET @Year_Month = CONCAT(@cur_Year, @cur_MONTH);
// get the last value for the current YEAR and MONTH
SET @max_ID = ( SELECT MAX(ID) 
                FROM    tableName 
                WHERE   ID LIKE CONCAT(@Year_Month, '-%'));
// get the last three characters from the id, convert in to
// integer and increment by 1
SET @last_ID = CAST(RIGHT(@max_ID, 3) AS SIGNED) + 1;
// pad zero on the left using LPAD and 
// concatenate it with YEAR and MONTH
SET @new_ID =   CONCAT(@Year_Month,'-',LPAD(CAST(@last_ID AS CHAR(3)), 3, '0'));
like image 116
John Woo Avatar answered Sep 18 '22 03:09

John Woo