SQL表中行的增量值

时间:2013-02-04 05:37:14

标签: c# sql sql-server

我在该列中有一个表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();

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

3 个答案:

答案 0 :(得分:4)

您可以直接执行UPDATE而无需运行select语句

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

以获得更好的代码质量,

  • 使用using声明进行适当的对象处理
  • 使用try-catch正确处理意外异常。
  • 参数化查询以阻止来自sql injection

答案 1 :(得分:2)

您可以使用set右侧的列名称。

 ConnectionDB AddMWeight = new 
 ConnectionDB("UPDATE Metal_Master SET Opening_Weight = Opening_Weight " +  10 + " WHERE Metal_Name='GOLD';");

答案 2 :(得分: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();