0

I have an invoice table in my database into which new invoices are inserted. Recently we have upgraded our services and have many users inserting invoices into the table. I have written a function that calculates the next invoice number in the sequence (the sequence isn't just sequential numbering).

MAX(CAST(SUBSTRING([InvoiceNumber], 3, LEN([InvoiceNumber]) - 2) AS INT)) FROM [Invoice] WHERE [InvoiceNumber] LIKE @Prefix + '%'

I now want to use this function in an insert statement as follows

INSERT INTO [Invoice]
([InvoicedTo]
 ,[InvoiceNumber]
 ,[InvoiceDate]
 ,[Description]
 ,[Amount])
VALUES
(@InvoicedTo
 ,NextInvoiceNumber(@Prefix)
 ,@InvoiceDate
 ,@Description
 ,@Amount)

What I want to make sure that using this insert statement will guarantee that the invoice number cannot be duplicated when multiple users are generating invoices. If it can result in duplicates, I would appreciate suggestions on how to stop any duplicates occuring.

Many Thanks, Paul

3 Answers 3

1

dont know if this is helpful

begin tran
declare @nextInvoiceNumber int = dbo.NextInvoiceNumber(@Prefix)

INSERT INTO [Invoice]
([InvoicedTo]
 ,[InvoiceNumber]
 ,[InvoiceDate]
 ,[Description]
 ,[Amount])
VALUES
(@InvoicedTo
 ,@nextInvoiceNumber
 ,@InvoiceDate
 ,@Description
 ,@Amount)

commit

another thing you could/should do is add a constraint to the table that requires it to be unique. then add error handling in the event this does happen that will just get you another number.

Sign up to request clarification or add additional context in comments.

Comments

0

No, it doesn't guarantee uniqueness.

You should wrap the call inside a serializable transaction.

Comments

0

You need to embed the insert script with in a transaction (Begin and Commit/Rollback) with appropriate isolation level.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.