I have an invoices table (innoDB) in which i need to set manually the progressive number for the next invoice. My code now is
SELECT MAX(invoice_n) FROM invoices WHERE invoice_y = 2013
and then regulary save the record putting the new invoice_n = max + 1. I have an index UNIQUE on invoice_n-invoice_y and I’m logging db errors, so I see that sometimes I have duplicate key entry errors, beacuse I have hundreds of different users connected. I put the code in a loop that continues until the invoice is generated, but i think there can be a more elegant solution, especially using transactions. I read a bit but I can’t understand how can I achive my result with transactions.
Any help?
You could use “AUTO_INCREMENT” in your column definition. You will see some gaps between numbers if the insertion fails.
Another alternative is creating a table with the last index per year (see comments) and follow the next steps:
Some links:
Another one, you could use an “optimistic approach” and repeat the select and the insert if it fails because a duplicate key.
I hope this helps you, any comment is welcome!