Home > Enterprise >  How to execute SQL query in ASP.NET MVC?
How to execute SQL query in ASP.NET MVC?

Time:01-26

How to use this query in ASP.NET MVC to copy data from table and send it to another table?

 INSERT INTO tblFee (AdmissionFee, Tuitionfee)
     SELECT AdmissionFee, TuitionFee 
     FROM tblFee

CodePudding user response:

Basically, you need a simple SqlConnection and SqlCommand to execute this query.

Done properly, it would look something like this:

string connectionString = "......";  // typically, you get this from a config file
string query = "INSERT INTO dbo.tblFee (AdmissionFee, Tuitionfee) SELECT AdmissionFee, TuitionFee FROM dbo.tblFee;";

// set up your connection and command, in "using" blocks
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmdInsert = new SqlCommand(conn, query))
{
    // open connection, execute query, close connection
    conn.Open();

    // since you are doing an "INSERT" - use "ExecuteNonQuery"
    // this returns only the number of rows inserted - no result set        
    int rowsInserted = cmdInsert.ExecuteNonQuery();
    
    conn.Close();
}

But with this, you're really just duplicating every row that's already in dbo.tblFee and re-inserting them back into the same table .... is that really what you're looking for??

CodePudding user response:

it doesnt working here is my controller

 public ActionResult feeappend(FeeMV feeMV)
    {
        string connectionString = "Data Source=CUTEBOY\\SQLEXPRESS;initial catalog=ShoolDB;integrated security=True"; 
        string query = "INSERT INTO dbo.tblFee (AdmissionFee, Tuitionfee) SELECT AdmissionFee, TuitionFee FROM dbo.tblFee";

        
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand cmdInsert = new SqlCommand(conn, query)) 
        {
            conn.Open();

            int rowsInserted = cmdInsert.ExecuteNonQuery();

            conn.Close();
        }


        return View(feeMV);
    }
  •  Tags:  
  • Related