通过向当前整数添加数字来更新 SQL 列

2021-09-16 00:00:00 sql vb.net sql-server sqlcommand

很简单,我不知道如何将文本框中的整数添加(即 +)到 SQL 字段中的整数.

Simple enough, I can't figure out how to add (that's +) an integer from a textbox to the integer in the SQL Field.

例如,SQL 字段中可能包含10",文本框中可能包含5".我想将这些数字加在一起以存储15",而无需下载 SQL 表.

So for example, the SQL Field may have '10' in it and the textbox may have '5' in it. I want to add these numbers together to store '15' without having to download the SQL Table.

包含要添加到 SQL 整数的整数的文本框是 tranamount.Text,SQL 表中的 SQL 列是 @ugpoints.请注意,如果没有+"——这在下面的代码中是公认的错误——tranamount.Text 的值被添加到表中没有问题,但它只是替换了原始值;这意味着最终结果在 SQL 字段中将是5".

The textbox that contains the integer to be added to the SQL integer is tranamount.Text and the SQL Column in the SQL Table is @ugpoints. Please note, without the '+' - which is in the below code and is admittedly wrong- the value of tranamount.Text is added to the Table without an issue, but it simply replaces the original value; meaning the end result would be '5' in the SQL Field.

构建它的正确方法是什么?我已经尝试了下面的代码,但这显然不起作用.

What would be the proper way to structure this? I've tried the below code, but that clearly doesn't work.

cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=@ugpoints WHERE Members_ID=@recevierID", con)

cmd.Parameters.AddWithValue("@recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("@ugpoints", + tranamount.Text) '<--- Value to add.
cmd.ExecuteNonQuery()

新手问题我知道,我是 vb 中的 SQL 新手.

Newbies question I know, I'm new to SQL in vb.

推荐答案

U_G_Studio字段的当前值,加上参数的值,重新赋值给U_G_Studio,但请记住,您需要将值作为整数传递,否则 AddWithValue 将传递一个字符串,并且您会收到来自数据库的转换错误.

Take the current value of the U_G_Studio field, add the value of the parameter and reassign to U_G_Studio, but keep in mind that you need to pass the value as an integer because otherwise the AddWithValue will pass a string and you get conversion errors coming from the db.

    cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=U_G_Studio + @ugpoints " & 
                         "WHERE Members_ID=@recevierID", con)
    cmd.Parameters.AddWithValue("@recevierID", tranmemberID.Text)
    cmd.Parameters.AddWithValue("@ugpoints", Convert.ToInt32(tranamount.Text))
    cmd.ExecuteNonQuery()

相关文章