简体   繁体   中英

Insert data to master detail tables by a stored procedure

I'm trying to add data to my master/detail table by using a stored procedure.

I tried this:

private void ekle()
{ 
    MySqlCommand cmd = new MySqlCommand("invinputfrompo", bag);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("?trnotes", MySqlDbType.Text).Value = tb1.Text;
    for (int i = 0; i <= dg1.Rows.Count - 1; i++)
    {
        if (Convert.ToBoolean(dg1.Rows[i].Cells[0].Value) == true)
        {

            cmd.Parameters.Add("?docno", MySqlDbType.VarChar).Value = dg1.Rows[i].Cells[9].Value.ToString();
            cmd.Parameters.Add("?idpodetails", MySqlDbType.Int32).Value = Convert.ToInt32(dg1.Rows[i].Cells[5].Value.ToString());
            cmd.Parameters.Add("?idmat", MySqlDbType.Int32).Value = Convert.ToInt32(dg1.Rows[i].Cells[6].Value.ToString());
            cmd.Parameters.Add("?sn", MySqlDbType.VarChar).Value = dg1.Rows[i].Cells[2].Value;
            cmd.Parameters.Add("?qty", MySqlDbType.Decimal).Value = Convert.ToDecimal(dg1.Rows[i].Cells[1].Value);
            //if (dg1.CurrentRow.Cells[4].Value.ToString() == "") { cmd.Parameters.Add("?shelflife", MySqlDbType.Date).Value = DBNull.Value; }
            //else { cmd.Parameters.Add("?shelflife", MySqlDbType.Date).Value = dg1.CurrentRow.Cells[4].Value.ToString(); }
            cmd.Parameters.Add("?shelflife", MySqlDbType.VarChar).Value = dg1.Rows[i].Cells[4].Value;
        }
    }
    cmd.Connection = bag;
    cmd.ExecuteNonQuery();
}

Only the first parameter "trnotes" will be added to the master table, other parameters will be added to the detail table.

I made loop like this but the way is not successful. it says you already defined "docno" (the first parameter in detail table)

Could you help for the data entry?

When your if statement runs for the second time, it tries to add docno to the list of parameters that was created on the first iteration. As docno was added in that first iteration, it already exists.

There are a couple of ways you could get around this:

  • Execute your stored procedure for each row. The downside is that you have the overhead of additional DB calls.
  • Use User-Defined Table Types . You would build up your table in C# and then pass that as a parameter to your stored procedure to insert into your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM