How can I use insert into with multiple tables?

Viewed 164

I'm trying to insert data for multiple tables at once. I'm trying join but I'm new to this and I hope you guys can help me.

I got 3 tables Malzemeler, Tarifler, MalzemelerveTarifler - all have some kind of a relationship through primary keys.

My tables columns like this

My code looks like this

con.Open();

SqlCommand komut = new SqlCommand("INSERT INTO Malzemeler.Malzemeİsmi, TariflerveMalzemeler.Gram_mL, TariflerveMalzemeler.Adet, Tarifler.Tarif_İsmi 
                                   VALUES (@Malzemeler.Malzemeİsmi, @TariflerveMalzemeler.Gram_mL, @TariflerveMalzemeler.Adet, @Tarifler.Tarif_İsmi)  
                                   WHERE Malzemeler JOIN TariflerveMalzemeler ON Malzemeler.Malzeme_ID = TariflerveMalzemeler.Malzeme_ID JOIN Tarifler ON TariflerveMalzemeler.Tarif_ID = Tarifler.Tarif_ID", con);

komut.Parameters.AddWithValue("@Tarif_İsmi", SqlDbType.VarChar).Value = txtYemek.Text;
komut.Parameters.AddWithValue("@Gram_mL", SqlDbType.VarChar).Value = txtGram1.Text;            
komut.Parameters.AddWithValue("@Adet", SqlDbType.VarChar).Value = txtAdet1.Text;
       
if (cbMalzeme1.SelectedItem == null)
{
    komut.Parameters.AddWithValue("@Malzemeİsmi", DBNull.Value);
}
else
{
    komut.Parameters.AddWithValue("@Malzemeİsmi", SqlDbType.VarChar).Value = cbMalzeme1.SelectedItem;
}
        
komut.ExecuteNonQuery();
con.Close();
2 Answers

You should use multiple INSERT queries, but you can create one Store Procedure and put your three INSERT or more in SP and call that SP just once from your code, and also you can use Transaction if it's important complete all INSERT data in three tables.

In Oracle you can make use of Insert all to insert into multiple table from single select statement.

I think you are using SQL Server ?

Related