user2755375
user2755375

Reputation: 17

add data into more than one table in sql server in c# syntax wanted

I have 2 tables in my database and I need to save the data to both tables in one method. I am getting an code unreachable error when I execute the following method. I need someone to tell me how to add this statement as a single insert statement. By the way PC_QA_REPORT_1 has a primary key and PC_QA_REPORT_2 has a foreign key to it, with Project_ID being a common column in both tables for this purpose.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Data;

namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        SqlConnection con = new SqlConnection("server = SP-DEV-MACHINE; Initial Catalog=The_Performance; Integrated Security=True");

        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}
        public string SubmitData(string pid, string ptitle, string date, string pqr, string pd, string ps, string pr, string pme, string pef, string pet, string psno, string pqs, string pds, string pmd, string pmr, string pmn)
        {



            SqlCommand cmd = new SqlCommand("INSERT INTO PC_QA_REPORT_1  (Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, Project_Strategic, Project_Relevant, Project_Monitoring_Eval, Project_Efficient, Project_Effective, Project_Sus_Nat_Own, Project_QA_Summary, Project_Document_Status) VALUES('" + pid + "','" + ptitle + "','" + date + "','" + pqr + "','" + pd + "','" + ps + "','" + pr + "','" + pme + "','" + pef + "','" + pet + "','" + psno + "','" + pqs + "','" + pds + "')", con);
            SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);

            con.Open();

            int i = cmd.ExecuteNonQuery();
            int x = command.ExecuteNonQuery();

            con.Close();
            return i.ToString();
            return x.ToString();

        }
        //public string MoreData(string pmd, string pmr, string pmn)
        //{

        //    SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);
        //    con.Open();
        //    int x = command.ExecuteNonQuery();
        //    con.Close();
        //    return x.ToString();
        //}

    }
}

Upvotes: 0

Views: 1007

Answers (4)

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

You can't insert into two tables without using two INSERT statements. It's just not possible. But you can put two INSERT statements into the same sql command object and run them in one transaction:

public int SubmitData(string pid, string ptitle, string date, string pqr, string pd, string ps, string pr, string pme, string pef, string pet, string psno, string pqs, string pds, string pmd, string pmr, string pmn)
{
    string sql = 
       "BEGIN TRANSACTION; " +

       "DECLARE @result int;"
       "INSERT INTO PC_QA_REPORT_1 (" +
         " Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, " +
         " Project_Strategic, Project_Relevant, Project_Monitoring_Eval, " + 
         " Project_Efficient, Project_Effective, Project_Sus_Nat_Own, " +
         " Project_QA_Summary, Project_Document_Status" +
      ") VALUES (" +
         "@pid, @ptitle, @date, @pqr, @pd, @ps, @pr, @pme, @pef, @pet, @psno, @pqs, @pds" + 
      ");" +
      " SET @result = @@rowcount; " +
      "INSERT INTO PC_QA_REPORT_2 (" + 
         " Project_M_Date, Project_M_Responsibility,Project_M_Notes" +
      ") VALUES(" + 
        " @pmd, @pmr, @pmn" +
      ");" + 
      " SELECT @result + @@rowcount; " +

      " COMMIT; ";

    //best to use a new connection object for each call to the database
    using (var con = new SqlConnection(" <connection string here> "))
    using (var cmd = new  SqlCommand(sql, con))
    {
        cmd.Parameters.Add("@pid", SqlDbType.Int).Value = int.Parse(pid);
        cmd.Parameters.Add("@ptitle", SqlDbType.NVarChar, 100).Value = ptitle;
        cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Parse(date);
        cmd.Parameters.Add("@pqr", SqlDbType.Float).Value = double.Parse(pqr);
        cmd.Parameters.Add("@pd", SqlDbType.NVarChar, 5).Value = pd;
        //You can fill in the rest of the parameters on your own

        con.Open();
        return (int)cmd.ExecuteScalar();
     }
}

As a bonus, this will also fix the horrible sql injection vulnerability in the original code.

Upvotes: 3

SlimPDX
SlimPDX

Reputation: 793

In regards to executing the two queries in one :

    SqlCommand cmd = new SqlCommand("INSERT INTO PC_QA_REPORT_1  (Project_ID, Project_Title, Date, Project_Quality_Rating, Project_Decision, Project_Strategic, Project_Relevant, Project_Monitoring_Eval, Project_Efficient, Project_Effective, Project_Sus_Nat_Own, Project_QA_Summary, Project_Document_Status) VALUES('" + pid + "','" + ptitle + "','" + date + "','" + pqr + "','" + pd + "','" + ps + "','" + pr + "','" + pme + "','" + pef + "','" + pet + "','" + psno + "','" + pqs + "','" + pds + "')", con);
    SqlCommand command = new SqlCommand("INSERT INTO PC_QA_REPORT_2 (Project_M_Date, Project_M_Responsibility,Project_M_Notes) VALUES('" + pmd + "','" + pmr + "','" + pmn + "')", con);

command += "; " + cmd;
int x = command.ExecuteNonQuery();
con.Close()
return x;

^ will work. As for the error you're getting... You can only return one thing from a function. You could, however, pass in integers as parameters ( by reference ) and modify them inside the function to get your return values

Upvotes: 1

Vivek
Vivek

Reputation: 2123

A. The unreachable code is because of 2 return statements. A method can only return once. Execution leaves the method after you return, hence any statements after it are unreachable code.

B. The way you are constructing your SQL commands is error prone and is open to SQL injections, please try using SQL parameters with a parametrized query instead.

Ex. ParameterizedQuery = Insert into Table1 values (@param1, @param2, @param3....)

C. Logically, this is a single insert - so you should think about doing in inside a DB transaction. If the first insert works and the second fails for some reason - you might end up with a bad state, depending on your actual data and requirements.

Upvotes: 1

userDEV
userDEV

Reputation: 535

Since your query command doesn't accept a returned value, by use of executenonquery, you should be able to use one long string in your first cmd statement. for example statement1; statement2. Separate statement with semicolon.

Upvotes: 0

Related Questions