C# SQL表中行的增量值

C# SQL表中行的增量值,c#,sql,sql-server,C#,Sql,Sql Server,我在该列中有一个表Metal\u Master,表中有Opening\u Weight我通过获取以前的值并添加一些值来更新该列的值,然后再次更新该值 我的代码是 ConnectionDB ReturnMWeight = new ConnectionDB("SELECT Opening_Weight FROM Metal_Master WHERE Metal_Name='GOLD';"); DataTable weighttd = ReturnMWeight.returntable(); Gold

我在该列中有一个表
Metal\u Master
,表中有
Opening\u 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();

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

您可以直接执行
更新
,而无需运行select语句

UPDATE Metal_Master 
SET Opening_Weight = Opening_Weight + new_Value
WHERE Metal_Name='GOLD'
为了提高代码质量

  • 使用
    使用
    语句进行正确的objet处理
  • 使用
    try catch
    正确处理意外异常
  • 参数化查询以防止
    sql注入

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

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

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();

后续问题:什么是
ConnectionDB
?ConnectionDB是我数据库相关函数的类谢谢@JW。你是对的,更新了我的答案,我希望一切都会好起来。