使用where子句c#插入语句

时间:2014-09-04 13:35:00

标签: c# sql asp.net

我试图根据cookie的值将详细信息插入表中。这是代码

   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子句中添加,如果所述行中“name”列的值与cookie匹配,它将把值插入某行。我不知道正确的语法 谢谢你的帮助

2 个答案:

答案 0 :(得分: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 in using声明。

答案 1 :(得分:0)

您正在寻找的内容有时被称为UPSERT。如果记录已存在,它将UPDATE,如果记录不存在,则为INSERT

SQL Server 2008及更高版本的此功能具有MERGE关键字。否则,我会使用具有正确逻辑的IF语句编写存储过程。