2014-09-04 44 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语句的存储过程。