【问题标题】:Insert statement with a where clause c#带有 where 子句的插入语句 c#
【发布时间】:2014-09-04 21:40:59
【问题描述】:

我正在尝试根据 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 匹配,它将在其中将值插入特定行。我不知道正确的语法 感谢您的帮助

【问题讨论】:

  • 感谢小伙伴们的帮助

标签: c# sql asp.net


【解决方案1】:

您需要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 声明。

【讨论】:

    【解决方案2】:

    您要查找的内容有时称为UPSERT。如果记录已经存在,它将UPDATE,如果不存在,它将INSERT

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      相关资源
      最近更新 更多