3

Metal_Master我在该列中有一个表,Opening_Weight我通过获取先前的值并添加一些值然后再次更新该值来更新该列的值。

我的代码是

ConnectionDB ReturnMWeight = new ConnectionDB("SELECT Opening_Weight FROM Metal_Master WHERE Metal_Name='GOLD';");
DataTable weighttd = ReturnMWeight.returntable();
GoldW = GoldW + Convert.ToDouble(weighttd.Rows[0][0].ToString());
ConnectionDB AddMWeight = new ConnectionDB("UPDATE Metal_Master SET Opening_Weight=" + GoldW + " WHERE Metal_Name='GOLD';");
AddMWeight.AddData();

但我想直接更新单个查询中的值请帮助..

4

3 回答 3

4

您可以UPDATE直接执行此操作而无需运行 select 语句,

UPDATE Metal_Master 
SET Opening_Weight = Opening_Weight + new_Value
WHERE Metal_Name='GOLD'

为了更好的代码质量,

  • 使用using声明进行正确的对象处理
  • 用于try-catch正确处理意外异常。
  • 参数化查询以防止sql injection
于 2013-02-04T05:41:14.110 回答
2

您可以使用集合右侧的列名。

 ConnectionDB AddMWeight = new 
 ConnectionDB("UPDATE Metal_Master SET Opening_Weight = Opening_Weight " +  10 + " WHERE Metal_Name='GOLD';");
于 2013-02-04T05:41:46.987 回答
0

试试这个 :

ConnectionDB AddMWeight = new ConnectionDB("UPDATE Metal_Master SET Opening_Weight=(SELECT SUM(Opening_Weight) AS Opening_Weight FROM Metal_master WHERE Metal_Name = 'GOLD')" + GoldW + " WHERE Metal_Name='GOLD';");
AddMWeight.AddData();
于 2013-02-04T05:41:56.487 回答