繁体   English   中英

SQL Server:使用更新命令时,数据在所有行中更新了相同的行值

[英]SQL Server : data updated same row values in all rows while using update command

使用update命令时,SQL Server数据在所有行中更新了相同的行值。

try {
    SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ToString());
    myConnection.Open();

    foreach (var i in ord) {
        SqlCommand sqlcm = new SqlCommand("update Orders Set CustomerID = @CustomerID, EmployeeID = @EmployeeID, ShipVia = @ShipVia, ShipName = @ShipName, ShipAddress = @ShipAddress, ShipCity = @ShipCity, ShipCountry = @ShipCountry", myConnection);

        sqlcm.Parameters.AddWithValue("@CustomerID", i.CustomerID);
        sqlcm.Parameters.AddWithValue("@EmployeeID", i.EmployeeID);
        sqlcm.Parameters.AddWithValue("@ShipVia", i.ShipVia);
        sqlcm.Parameters.AddWithValue("@ShipName", i.ShipName);
        sqlcm.Parameters.AddWithValue("@ShipAddress", i.ShipAddress);
        sqlcm.Parameters.AddWithValue("@ShipCity", i.ShipCity);
        sqlcm.Parameters.AddWithValue("@ShipCountry", i.ShipCountry);

        sqlcm.ExecuteNonQuery();
        sqlcm.Dispose();
    }

    myConnection.Close();
}

使用此C#代码,结果将在所有行中得到相同的数据:

10248   VINET   5   3   Vins et alcools Chevalier   59 rue de l'Abbaye  Reimsesddf  France
10249   VINET   5   3   Vins et alcools Chevalier   59 rue de l'Abbaye  Reimsesddf  France
10250   VINET   5   3   Vins et alcools Chevalier   59 rue de l'Abbaye  Reimsesddf  France

我已将Reims更改为Reimsesddf ,以获得10248 id,但它在所有行中均得到反映,其他数据也将在所有行中进行更新。

我怎样才能解决这个问题 ?

您的update语句缺少where条件-因此它将更新表中的所有记录:

update Orders Set 
  CustomerID = @CustomerID, EmployeeID= @EmployeeID, 
  ShipVia=@ShipVia, ShipName=@ShipName,
  ShipAddress=@ShipAddress,ShipCity=@ShipCity,
  ShipCountry= @ShipCountry

where添加一些条件(按记录ID或其他方式)以防止出现这种情况:

update Orders Set 
  CustomerID = @CustomerID, EmployeeID= @EmployeeID, 
  ShipVia=@ShipVia, ShipName=@ShipName,
  ShipAddress=@ShipAddress,ShipCity=@ShipCity,
  ShipCountry= @ShipCountry
where ID = @ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM