How can I create a unique invoice number?

jewel 901 Reputation points
2023-10-27T15:16:07.01+00:00

I want to use a unique invoice number in my work. I am using SQL Server database.

I want an invoice number to be generated which will have current year first with autoincrement number. When the year changes to a new year, the invoice number will start over.
For example, 2023/00001
2023/00002
When the new year comes the invoice number will be-
2024/00001
2024/00002
This will continue.
It would be helpful if any experienced help. thanks in advance


 public class tbl_Sell
    {
        [Key]
        public int SelliD { get; set; }
        public String InvoiceNO { get; set; }
        public int productID { get; set; }
        public int Qty { get; set; }
       
    }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,560 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 65,316 Reputation points
    2023-10-27T21:28:59.04+00:00

    if you use a table with a max value, be sure to proper locking to prevent race conditions or use a single statement:

    create table NextOrderNumber
    (
        Year int not null,
        Number int not null
    )
    go
    
    declare @year int = 2023;
    declare @number int = 1;
    
    merge NextOrderNumber as n
    using (select @year as year) as y 
       on n.Year = y.Year 
    when matched then
        update set 
            Number = Number + 1,
            @number = Number + 1 
    when not matched then
        insert (Year, Number)
        values (y.year, @number);
    
    select cast(@year as varchar(4)) + right('0000' + cast(@number as varchar(5)), 4); 
    
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.