I have this code below to generate series number
upon saving of the user. But my problem is if the user of the system save at the same time(many user)
it has a possibility to have a duplicate series number.
public string GenerateSeriesNumber(string code, Entities db, string Ctrl)
{
string year = DateTime.Now.Year.ToString().Substring(2);
string prev_ctrls = "";
var tbl = db.SeriesTable.Where(a => a.SeriesNo.Contains(Ctrl)).OrderByDescending(a => a.SeriesNo);
foreach (var item in tbl.ToList())
{
string[] current_srs = item.SeriesNo.Split('-');
if (prev_srs == "")
prev_srs = item.SeriesNo;
int aaa = Convert.ToInt32(prev_srs.Split('-')[3]);
int bbb = Convert.ToInt32(current_srs[3]);
if (aaa < bbb)
prev_srs = item.SeriesNo;
}
string Series_No = "";
if (tbl != null)
{
string[] LastSeries_No = prev_srs.Split('-');
if (LastSeries_No.Length == 4)
{
LastSeries_No[3] = Int32.Parse(LastSeries_No[3]) + 1 + "";
for (int i = LastSeries_No[3].Length; i < 7; i++)
{
LastSeries_No[3] = "0" + LastSeries_No[3];
}
LastSeries_No[1] = code.ToUpper();
Series_No = String.Join("-", LastSeries_No);
return Series_No;
}
}
return Series_No;
}
I tried to execute this in my SQL (I am using SQL Server 2017)
but one of them encountered an error and didn't save
ALTER TABLE dbo.SeriesTable
ADD CONSTRAINT UC_LT UNIQUE (SeriesNo);