How to generate custom unique string in C# and SQL Server and ensure that it is always unique

sqougxex  于 12个月前  发布在  C#
关注(0)|答案(1)|浏览(105)

I have a requirement to generate RecordNo as follows:

ABC-240001  
ABC-240002  
ABC-240003

Here "ABC-" will remain fixed while "24" is current year and "0001" is 4 digit number which is auto incremented. So when 2025 starts, it will become ABC-250001

I have an application where user fills out form and this number needs to be generated and stored in SQL Server.

I am thinking about getting last RecordNo of current year from database, then increment it by 1, and then save it in database.

What is the best way to do it and how do I ensure that it always generates unique number because two or more people may be submitting form simultaneously?

ukqbszuj

ukqbszuj1#

Here is the solution. Set this script to run as a job in SQL Server Agent on 1st of every month. On 1st Jan of every year, it will reset counter to 0001.

IF (DATEPART(DAY, GETDATE()) = 1 AND DATEPART(MONTH, GETDATE()) = 1)
BEGIN
    DECLARE @reseedValue INT
    SET @reseedValue = CAST(CONCAT(CAST((Year(GetDate()) - 2000) AS VARCHAR(6)), '0000') AS INT)
    DBCC CHECKIDENT ('[TestTable]', RESEED, @reseedValue);
END

相关问题