【问题标题】:insert code error插入代码错误
【发布时间】:2018-10-31 18:58:15
【问题描述】:
insert into customer (Advance,status)
values(@Advance,@status)
where Name='" + txtcname.Text.Trim() + "'";

在上面的插入语句中,要根据条件插入 2 个值,但我在 where 条件中遇到错误...

关键字 where 附近的语法不正确

这是错误

【问题讨论】:

    标签: c# sql .net sql-server-2008


    【解决方案1】:

    插入查询不需要Where子句。就写吧

    insert into customer (Advance, status) values(@Advance, @status)

    您是要插入还是更新?如果您需要更新现有记录,请使用更新而不是插入,如下所示:

    update customer set Advance=@Advance, status=@status 
    where Name='" + txtcname.Text.Trim() + "'";
    

    编辑

    上述更新查询将达到目的,但建议使用存储过程/参数化查询以确保 SQL 注入安全。您应该遵循以下使用方法:

    Private void UpdateRecord(string advance,string status, string name)
    {
    //SqlConnection con
    SqlCommand cmdUpdate = new SqlCommand("update customer set Advance = @Advance, status = @Status where Name=@Name", con);
                cmdUpdate.Parameters.AddWithValue("@Advance", advance);
                cmdUpdate.Parameters.AddWithValue("@Status", status);            
                cmdUpdate.Parameters.AddWithValue("@name", name);
                cmdUpdate.ExecuteNonQuery();
    
    }
    

    按如下方式传递您的数据:

    UpdateRecord(@Advance,@Status,txtcname.Text.Trim());
    

    【讨论】:

    • 虽然您的答案可能是正确的,但它还应该更改where 子句以使用参数,并解释原因。
    • Where子句不能和insert一起使用,语法示例见这里:stackoverflow.com/questions/13386894/sql-server-insert-example, w3schools.com/sql/sql_insert.asp
    • 除非你做一个insert into tableA select * from tableB where
    • 1. Where 子句可以与 insert 一起使用,如果它是 insert...select。 2. 我同意 OP 可能正在寻找 update 声明,而不是 insert 声明。 3. your update 语句中的where 子句没有参数化,使得该语句容易受到SQL Injection 攻击。解决这个问题,你也会得到我的支持。
    • @ZoharPeled,根据文档 insert..select 仍然没有插入的 where 部分而不是 select 的部分。有一个解决方法来组合两个查询并不意味着它是插入的一部分。
    【解决方案2】:

    您不能在插入语句中使用“where”。 为了达到同样的效果,你可以插入所有条目并删除错误的。

    您可以在插入之后使用选择语句,您可以在其中从一个表中选择条目到另一个表中。这也可能是您的解决方案。

    Insert into customer (advance, status) values (...)
    select advance, status
    from anotherCustomerTable
    where ... 
    

    附:也尝试准备 where-part。

    【讨论】:

      【解决方案3】:

      您不能在 where 子句中添加值。您可以通过以下方式实现此目的 如果你真的想插入新行,你可以按照@Munawar 解决方案

      insert into customer (Advance, status)
      
      SELECT @Advance,@status
      FROM  customer where Name='" + txtcname.Text.Trim() + "'"
      

      【讨论】:

        猜你喜欢
        • 2017-12-03
        • 2016-06-08
        • 1970-01-01
        • 1970-01-01
        • 2012-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多