2013-02-04 43 views
3

我有一個表Metal_Master在那個列中有Opening_Weight我正在更新該列的值,通過獲取以前的值並添加一些值然後再次更新該值。在SQL表中的行增量值

我對這個代碼是

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

你可以直接做UPDATE不運行SELECT語句,

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

爲了更好的質量的代碼,

  • 使用using陳述適當的對象處理
  • 使用try-catch正確處理意外的異常。
  • 參數化查詢,以防止sql injection
+0

*跟進的問題:什麼是'ConnectionDB' * –

+0

ConnectionDB是我的數據庫相關的功能 – Milind

2

你可以在設置中的右側使用的列名。

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

感謝@JW類。你是對的,更新我的答案,我希望它會沒事的。 – Adil

+0

這是更好的'+ 1' –

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

太複雜':(' –