Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Auto generate ID number as yyyynnnn where ‘yyyy’ is current calendar year and ‘nnnn’ is the next ID serial number for the calendar year.
e.g. 20200001
Note: ‘nnnn’ serial number should start with 1 when calendar year changes.

What I have tried:

Auto generate ID number as yyyynnnn where ‘yyyy’ is current calendar year and ‘nnnn’ is the next ID serial number for the calendar year.
e.g. 20200001
Note: ‘nnnn’ serial number should start with 1 when calendar year changes.
Posted
Updated 8-Sep-20 20:37pm
Comments
Maciej Los 9-Sep-20 2:21am    
What have you tried so far? Where did you stuck?

Set up an IDENTITY field to autoincrement and provide a unique value per row.
Then set up a Computed Column[^] which generates your year based ID.
Generate your table with three columns:
ID (INT, IDENTITY)
InsDate (DATE)
YearID (NVARCHAR(8)
Create a scalar function:
SQL
CREATE FUNCTION [dbo].[fnGetYearID] 
(
	@DT DATE
)
RETURNS NVARCHAR(8)
AS
BEGIN
	DECLARE @Result NVARCHAR(8)
    SET @Result = cast(year(@DT) as varchar) + (SELECT RIGHT('0000' + CAST(COUNT(*) AS NVARCHAR(4)), 4) FROM MyTable WHERE YEAR(InsDate) = YEAR(@DT))
	RETURN @Result

END
Change the design of your table to make the YearID column a computed column, with the Computed Column Specification set to:
([dbo].[fnGetYearID]([InsDate]))

Now try adding a column with a date and no other data.
 
Share this answer
 
Comments
Maciej Los 9-Sep-20 3:35am    
5ed!
int year = date.Year;
int MonthPart = date.Month;
int dayPart = date.Day;
int OrderNo = 000;
string ON = "";
var lstData = dbEntities.TableName.OrderByDescending(company => company.ModifiedDate).Take(1).ToList();

if (lstData != null && lstData.Count() > 0 && MonthPart != 01 && dayPart != 01)
            {
                foreach (var item in lstData)
                {
                    ON = item.TestOrderNo.ToString().Substring(item.TestOrderNo.ToString().Length - 3);
                    OrderNo = int.Parse(ON) + 1;
                }
            }
            else
            {
                OrderNo = 001;
            }
TON = YearPart + "-" + OrderNo.ToString().PadLeft(3, '0');
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900