I need to know what order number has been written to the database. To achieve this I use the SQL expression EXECUTESCALAR.
I debugged the program and monitored the database. The record is written once into the Database when I execute the 2nd Command it writes the same record a 2nd time. Can you help me out what I need to change so it does not write 2 records and I get my Order number back?
This is my code:
public static int CreateDocumentNumber(string userId, string todaysDate, decimal docprice, decimal docpaid, int packageId, int orderstatus)
{
int orderId = 0; //return value order Id
//create order
string connectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string insertSql = "INSERT INTO [dbo].[LD_Orders](TD_OrdUserID, TD_OrdDate, TD_OrdCost, TD_OrdPaid, TD_OrdPackage, TD_OrdStatus)" +
" VALUES (@UserId, @Date, @Cost, @Paid, @Package, @Status);SELECT SCOPE_IDENTITY()";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.Add("@UserId", SqlDbType.VarChar).Value = userId;
myCommand.Parameters.Add("@Date", SqlDbType.Date).Value = todaysDate;
myCommand.Parameters.Add("@Cost", SqlDbType.Decimal).Value = docprice;
myCommand.Parameters.Add("@Paid", SqlDbType.Decimal).Value = docpaid;
myCommand.Parameters.Add("@Package", SqlDbType.Int).Value = packageId;
myCommand.Parameters.Add("@Status", SqlDbType.Int).Value = orderstatus;
myCommand.ExecuteNonQuery(); <---- FIRST RECORD WRITTEN
// time to collect the last order id
orderId = Convert.ToInt32(myCommand.ExecuteScalar()); <---- SECOND RECORD WRITTEN
myConnection.Close();
}
return orderId;
}