sbrbot
sbrbot

Reputation: 6469

Auto-increment - automatic reset for each year

MySQL/InnoDB

In my case my receipts should be counted on yearly basis; 1/2015, 2/2015 ... 556/2015 and so on. When next year comes, the counter should start from 1 again and receipts should be counted as 1/2016, 2/2016 ...

How to define auto_increment field which will reset itself on yearly basis?

RCID | RCNO | RCYEAR | ...
=====+======+========+====
 200 |    1 |   2015 |
 201 |    2 |   2015 |
 ... |  ... |   2015 |     
 756 |  556 |   2015 |     <- last receipt in 2015
 757 |    1 |   2016 |     <- yearly counter restarted

NOTE: RCID is standard PK auto incremented field.

Upvotes: 3

Views: 2082

Answers (1)

sbrbot
sbrbot

Reputation: 6469

After help from @RickJames the solution is:

CREATE TRIGGER ReceiptNumber BEFORE INSERT ON receipts FOR EACH ROW
BEGIN
  SET NEW.rcyear=YEAR(NOW());
  SET NEW.rcno=(SELECT IFNULL(MAX(rcno),0)+1 FROM receipts WHERE rcyear=YEAR(NOW()));
END;

Upvotes: 5

Related Questions