I’m developing a site in asp.net MVC that should generate invoices.
After some reading regarding the generation of the invoice numbers, my understading is to use a trigger or a stored procedure to be sure to have the number generated correctly without skipped or duplicated numbers, due to concurrent inserts of invoices.
For what I understand, the best approach would be to create a trigger, in the after insert of my invoices table, that does the work in a single transaction.
So I came up with this, that seems to work nice (more tests this weekend)
CREATE TRIGGER Invoices_SetInvoiceNum ON Invoices AFTER INSERT
AS
declare @next int
Begin tran
set nocount on
update counters set @next=InvoiceNum=InvoiceNum+1
update Invoices set InvoiceNum = @next from inserted i join Invoices p on p.Id = i.Id
IF @@ERROR = 0
COMMIT TRAN
ELSE
ROLLBACK TRAN
- Is this a good approach or there is a better way to be sure that the number will never be duplicated or skipped?
- It’s more safe to use also a table/record lock? if yes could you suggest an integration to my trigger?
Thanks in advance for any insight on this topic.
A better approach would be make the invoice column a Identity column and let it increment itself.
See this runnable example