Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends
i have a form and a button, and two tables in sql server,say table1 and Table2, the primary key(which is also an identity column) of table1 is a foreign key in table2. now i am inserting into this two tables by creating a method to insert into table2 and under the button click i am creating insert statement for table1 and retrieving the primary key to a label Table1CodeLabel and passing the Text of the label to table2 here is my code this may help you understand what am trying to say.

C#
private void InsertTable2()
       {
               try
               {
                   con.Open();
                   if (cmd.Parameters.Count == 0)
                   {
                       cmd.Connection = con;
                       this.cmd.CommandText = "insert into Table2([Code/ID], Description, [Long Name],[Standard Charge],[Standard Cost],RVU,[Note Template],Comment,Category,Table1Code) values(@Code, @Description,@LongName,@StandardCharge,@StandardCost,@RVU,@NoteTemplate,@Comment,@Category,@Table1Code)";
                       this.cmd.Parameters.Add("@Code", System.Data.SqlDbType.Int);
                       this.cmd.Parameters.Add("@Description", System.Data.SqlDbType.VarChar, 50);
                       this.cmd.Parameters.Add("@LongName", System.Data.SqlDbType.VarChar, 50);
                       this.cmd.Parameters.Add("@StandardCharge", System.Data.SqlDbType.Money);
                       this.cmd.Parameters.Add("@StandardCost", System.Data.SqlDbType.Money);
                       this.cmd.Parameters.Add("@RVU", System.Data.SqlDbType.Int);
                       this.cmd.Parameters.Add("@NoteTemplate", System.Data.SqlDbType.VarChar, 50);
                       this.cmd.Parameters.Add("@Comment", System.Data.SqlDbType.VarChar, 50);
                       this.cmd.Parameters.Add("@Category", System.Data.SqlDbType.VarChar,
                       this.cmd.Parameters.Add("@Table1Code", System.Data.SqlDbType.VarChar, 50);

                   }
                   this.cmd.Parameters["@Code"].Value = this.txtID.Text;
                   this.cmd.Parameters["@Description"].Value = this.txtDescription.Text;
                   this.cmd.Parameters["@LongName"].Value = this.txtLongName.Text;
                   this.cmd.Parameters["@StandardCharge"].Value = this.txtStandardCharge.Text;
                   this.cmd.Parameters["@StandardCost"].Value = this.StandardCost.Text;
                   this.cmd.Parameters["@RVU"].Value = this.domainUpDown1.Text;
                   this.cmd.Parameters["@NoteTemplate"].Value = this.cbNoteTemplate.Text;
                   this.cmd.Parameters["@Comment"].Value = this.txtComment.Text;
                   this.cmd.Parameters["@Category"].Value = this.cbCategory.Text;
                   this.cmd.Parameters["@Table1Code"].Value = this.Table1CodeLabel.Text; //the primary key from table1
                   cmd.ExecuteNonQuery();

                   MessageBox.Show("inserted to Table2");
                  // con.Close();
               }
               catch (System.Exception exp)
               {
                   MessageBox.Show("Error!  " + exp.Message);
               }
               finally
               {
                  this.con.Close();
               }
           }

       }


then under the button click is the code that is inserting to table1

C#
 private void btnSaveAddedItem_Click(object sender, EventArgs e)
        {
                try
                {
                    con.Open();
                    if (cmd1.Parameters.Count == 0)
                    {
                        cmd1.Connection = con;
                        this.cmd1.CommandText = "INSERT INTO table1([Charge Type],[Charge Category],[Description],[Standard Charge])output inserted.[Code] values( @ChargeType,@ChargeCategory,@Descriptions,@StandardCharges)";

                        this.cmd1.Parameters.Add("@ChargeType", System.Data.SqlDbType.VarChar, 50);
                        this.cmd1.Parameters.Add("@ChargeCategory", System.Data.SqlDbType.VarChar, 50);
                        this.cmd1.Parameters.Add("@Descriptions", System.Data.SqlDbType.VarChar, 50);
                        this.cmd1.Parameters.Add("@StandardCharges", System.Data.SqlDbType.Money);
                    }
                    this.cmd1.Parameters["@ChargeType"].Value = this.TypeLabel.Text;
                    this.cmd1.Parameters["@ChargeCategory"].Value = this.cbCategory.Text;
                    this.cmd1.Parameters["@Descriptions"].Value = this.txtDescription.Text;
                    this.cmd1.Parameters["@StandardCharges"].Value = this.txtStandardCharge.Text;

//this is where the retrieve primary key will be passed to the the label table1CodeLabel
                    Int32 newid = (Int32)cmd1.ExecuteScalar();
                    Table1CodeLabel.Text = newid.ToString();
                    con.Close();

//this is the code that insert to table2 after the primary key of table1 has been passed to the label it will then be inserted to the table2
                    InsertTable2();

                    MessageBox.Show("Done successfully");

                }
                catch (SqlException exp)
                {
                    MessageBox.Show("Error carrying out operation, please try again but if problem persist, contact administrator " + exp.Message);

                }
                catch (System.Exception exp)
                {
                    MessageBox.Show("System Error! contact Administraor " + exp.Message);
                }
                finally
                {
                  con.Close();

                }
            }
        }


hope the code explains it better, but my problem now is that i do not know if this is the best way to do this because there could be situations when the insert for tale1 may execute and the one for table2 may not insert successfully and vise versa, is there any way to put a check so if table1 insert successfully table2 must insert and if table1 does not insert table2 will not insert or please suggest a better a for me to do this.
Thanks in advance
Posted

Hi,
Please use transaction management.

SQL
BEGIN TRANSACTION
BEGIN TRY
	--Your insert query for both tables/ Some More SQL
	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	
	BEGIN
		ROLLBACK TRANSACTION;
	END;
END CATCH
 
Share this answer
 
v2
Comments
Ese Ochuko 27-Feb-14 6:27am    
hi thank you very much for your response but am using visual studio 2010 can you just give me a complete code on how to do this from visual studio because i noticed that visual studio is not recognizing "BEGIN TRANSACTION or BEGIN TRY", so can you just tell me how to do it, break it down so i can understand it very well.
thank you very much in advance
may be you can have only one procedure with begin transaction commit and rollback options. in this way you can be sure that if data save it should save for both table otherwise it gets rollback.
 
Share this answer
 
you can use "Solution 2" server side or transaction client side
best way is "Solution 2"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900