Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - Get an identity value in a controller for INSERT (Execute Insert command and return inserted Id in Sql)

Currently, I am using MVC on creating a project. Now I want to insert an Identity ID value into an INSERT statement.

In my controller:

string payment = @"INSERT INTO Payment(Payment_Method,Currency_Type,Total_Amount) 
                         VALUES('{0}','{1}',{2})";
        int pay = DBUtl.ExecSQL(payment, "Cash", currency,total);
        if (pay == 1)
        {
            string pid = "SELECT TOP 1 Payment_id FROM Payment ORDER BY Payment_id DESC";
            int paymentid = DBUtl.ExecSQL(pid);
        if (cart.Count() != 0)
        {
            string order = @"INSERT INTO [Order](Order_Name,Order_Description,Order_Quantity,Payment_Id) 
                     VALUES('{0}','{1}',{2},{3})";

Now, I want to the payment_id that already been inserted into the payment table which is the first statement and retrieve the payment_id and use it into the INSERT statement for the Order table

How can I achieve that?

Please Help

Thank you

question from:https://stackoverflow.com/questions/65856775/get-an-identity-value-in-a-controller-for-insert-execute-insert-command-and-ret

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually, DBUtil code consists of:

public static int ExecSQL(string sql, params object[] list)
{
    List<String> escParams = new List<String>();

    foreach (object o in list)
    {
        if (o == null)
            escParams.Add("");
        else
            escParams.Add(EscQuote(o.ToString()));
    }

    DB_SQL = String.Format(sql, escParams.ToArray());

    int rowsAffected = 0;

    using (SqlConnection dbConn = new SqlConnection(DB_CONNECTION))
    using (SqlCommand dbCmd = dbConn.CreateCommand())
    {
         try
         {
              dbConn.Open();
              dbCmd.CommandText = DB_SQL;
              rowsAffected = dbCmd.ExecuteNonQuery();
         }
         catch (System.Exception ex)
         {
              DB_Message = ex.Message;
              rowsAffected = -1;
         }
     }

     return rowsAffected;
}

And as you know ExecuteNonQuery denotes the numbers affecting the row

So, You can do as shown below:

FOR SQL SERVER 2005 and above

   using (SqlConnection con=new SqlConnection(@"Your connectionString"))
    {
        using(SqlCommand cmd=new SqlCommand("INSERT INTO Payment(Payment_Method,Currency_Type,Total_Amount) output INSERTED.Payment_id VALUES(@Payment_Method,@Currency_Type,@Total_Amount)",con))
        {
            cmd.Parameters.AddWithValue("@Payment_Method", "Cash");
            cmd.Parameters.AddWithValue("@Currency_Type", currency);
            cmd.Parameters.AddWithValue("@Total_Amount", total);
            con.Open();
        
            int payment_id =Convert.ToInt32(cmd.ExecuteScalar());
        
            if (con.State == System.Data.ConnectionState.Open) 
                con.Close();
        
            return payment_id ;
        }
}

also, you can change your query to:

"INSERT INTO Payment(Payment_Method,Currency_Type,Total_Amount) VALUES(@Payment_Method,@Currency_Type,@Total_Amount)"; SELECT SCOPE_IDENTITY()" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...