2016-01-12 38 views
-2

如何更新字段以將值添加到現有值? 例如,我有下面的產品表。如何使用C#中的sql查詢將值添加到現有值

  product quantity 
       x   4 
       y   5 
       z   3 

有沒有辦法簡單地增加數量的價值? 像

int qn = int.Parse(TextBox3.Text) 
SqlCommand cmd1 = new SqlCommand("update product set group1 = group1 + qn where productname = '@productname'", con); 
cmd1.Parameters.Add(new SqlParameter("@productname", TextBox1.Text)); 

我想文本框的值增加4使信用進行更新,其中產品=「X」 我收到錯誤「無效列名‘QN’」(組1 = 1組+ QN) 。請建議我解決這個錯誤?

+0

您的表不必須組別1列 –

+0

我提到的更新詢問 – Meena

+0

量爲1組@米娜爲什麼?你爲什麼不使用你的_real_列名? –

回答

1

你必須添加qn作爲另一個參數,並與查詢一起傳遞,所以您的查詢就會像下面這樣:

SqlCommand cmd1 = new SqlCommand("update product set group1 = group1 + @qn where productname = @productname", con); 
cmd1.Parameters.Add(new SqlParameter("@qn", qn)); 
cmd1.Parameters.Add(new SqlParameter("@productname", TextBox1.Text)); 
+0

group1不是列名。它的數量。 –

0

刪除SQL字符串中參數的單引號。

"update product set group1 = group1 + qn where productname = '@productname'" 
                  //^^   ^^ 

使用參數時不需要單引號。

另外也爲qn添加參數。 像:

int qn = int.Parse(TextBox3.Text) 
SqlCommand cmd1 = new SqlCommand("update product set group1 = group1 + @qn where productname = @productname", con); 
cmd1.Parameters.Add(new SqlParameter("@productname", TextBox1.Text)); 
cmd1.Parameters.Add(new SqlParameter("@qn", qn)); 

,如果你在using聲明中附上您的命令和連接對象這是更好,這將保證資源的妥善處置。

+1

我的代碼工作正常,此後我將添加「使用」語句。感謝您的建議,... – Meena

相關問題