I have this table called ArticleBarCode :
IntheCodecolumnIneedtoenterasequentialnumber,ieIhavetoreadthemaximumnumberthatisthereandinsertthenextonethatisavailable!Ihavetousethefollowinglineofcodetoseewhattheavailablevalueis:
SELECTISNULL(MAX(Code),0)+1FROMArticleBarCode
Doesanyoneknowhowtohelpwiththissituation?Thanks!
ThisisthecodeIusetoinsertvaluesintothistable:
conn.Open();comm.CommandText=@"INSERT INTO ArticleBarCode(Code, Code_Article, BarCode, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn, IsDeleted)
VALUES (@code, @codearticle, @barcode, 1, @date, 1, @date, 0)";
comm.Parameters.AddWithValue("@code", next);
comm.Parameters.AddWithValue("@codearticle", code);
comm.Parameters.AddWithValue("@barcode", numbercode);
comm.Parameters.AddWithValue("@date", DateTime.Now);
comm.ExecuteNonQuery();
conn.Close();
That next has to be the sequential value! The rest works everything.
I have this code that can fetch the next available value and then try to insert:
conn.Open();
SqlCommand cmd5 = new SqlCommand("SELECT ISNULL(MAX(Code), 0) + 1 FROM ArticleBarCode", conn);
Int32 next = (Int32) cmd5.ExecuteScalar();
conn.Close();
conn.Open();
comm.CommandText = @"INSERT INTO ArticleBarCode(Code, Code_Article, BarCode, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn, IsDeleted)
VALUES (@code, @codearticle, @barcode, 1, @date, 1, @date, 0)";
comm.Parameters.AddWithValue("@code", next);
comm.Parameters.AddWithValue("@codearticle", code);
comm.Parameters.AddWithValue("@barcode", numbercode);
comm.Parameters.AddWithValue("@date", DateTime.Now);
comm.ExecuteNonQuery();
conn.Close();
But when I do this, it gives me this error:
The INSERT statement conflicts with the FOREIGN KEY constraint "FK_ArticleBarCode_Article". The conflict occurred in database "CardozuGestDB", table "dbo.Article", column 'Code'.