2014-09-04 123 views
1

我試圖根據cookie中的值將詳細信息插入表中。這裏是代碼插入帶有where子句的語句c#

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString); 
     conn.Open(); 
     string insertQuery = "insert into Details (Employees, Performance, TotalPerformance, Attitude, TotalAttitude) values(@employees, @performance ,@totalPerformance, attitude, totalAttitude)"; 
     SqlCommand com = new SqlCommand(insertQuery, conn); 
     com.Parameters.AddWithValue("@employees", Request.QueryString["employees"]); 
     com.Parameters.AddWithValue("@performance", totalPer.ToString()); 
     com.Parameters.AddWithValue("@totalPerformance", totalPercent.ToString()); 
     com.Parameters.AddWithValue("@attitude", totalAtt.ToString()); 
     com.Parameters.AddWithValue("@totalattitude", totalPercent.ToString()); 



     com.ExecuteNonQuery(); 

這工作正常,但在管柱嵌查詢行我想,如果說對列「名稱」中的值where子句,在那裏將值插入到某個行中添加行匹配一個cookie。我不知道正確的語法 感謝您的幫助

+0

感謝您的幫助夥伴 – user3542214 2014-09-04 13:40:09

回答

4

您需要一個UPDATE語句,而不是INSERT語句,因爲您要修改現有記錄。

using (
    SqlConnection conn = 
     new SqlConnection(
      ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) 
{ 
    conn.Open(); 
    string updateQuery = 
     @"UPDATE Details 
     SET Employees = @employeee, 
     Performance = @performance , 
     TotalPerformance = @totalPerformance, 
     Attitude = @attitude, 
     TotalAttitude = @totalattitude 
     WHERE yourField = @yourConditionValue"; 

    using (SqlCommand com = new SqlCommand(updateQuery, conn)) 
    { 
     com.Parameters.AddWithValue("@employees", Request.QueryString["employees"]); 
     com.Parameters.AddWithValue("@performance", totalPer.ToString()); 
     com.Parameters.AddWithValue("@totalPerformance", totalPercent.ToString()); 
     com.Parameters.AddWithValue("@attitude", totalAtt.ToString()); 
     com.Parameters.AddWithValue("@totalattitude", totalPercent.ToString()); 
     com.Parameters.AddWithValue("@yourConditionValue", yourValue); 
     com.ExecuteNonQuery(); 
    } 
} 

+1,對於你的問題,另一件事情,enclose your Command and Connection object inusing語句中使用的參數。

+0

感謝您的幫助 – user3542214 2014-09-04 13:40:26

+1

這工作完美,很好的幫助,謝謝 – user3542214 2014-09-04 13:56:46

0

你在找什麼有時被稱爲UPSERT。如果它已經存在,它將會記錄UPDATE;如果它不存在,則會記錄INSERT

對於此功能,SQL Server 2008和更高版本具有MERGE關鍵字。否則,我會用正確的邏輯寫一個IF語句的存儲過程。