如何扣除SQL数据库中的数量?

时间:2019-08-26 06:56:40

标签: mysql sql vb.net xampp

enter image description here我正在尝试获取我数据库中“数量”和“商品购买”之间的差异,并根据两者之间的差异来更新“数量”列。

我为此尝试了不同的SQL代码,但是我总是遇到相同的错误

尝试             getConnection()

        sql = "SELECT (Quantity - ItemBought) AS [Quantity] FROM products WHERE ProductCode = @ProductCode;"

        cmd = New MySqlCommand
        With cmd
            .Connection = conn
            .CommandText = sql
            .Parameters.Clear()

            .Parameters.AddWithValue("@ProductCode", formPOS.ProductCodeTB.Text)
            .Parameters.AddWithValue("@ItemBought", formInventory.quantityTB.Text)
            result = cmd.ExecuteNonQuery()
            If result = 0 Then
                MsgBox("Error in updating the selected product!")
            Else
                MsgBox("Successfully updated the selected product!")
            End If"

3 个答案:

答案 0 :(得分:0)

使用修改后的值更新表并重新填充gridview。它将直接更改表格值。

如果您要临时更改数据,请按照以下步骤操作:

"SELECT Quantity AS [Quantity] FROM products WHERE ProductCode = @ProductCode;"

然后减去ItemBought,然后显示在gridview中。

答案 1 :(得分:0)

您正在尝试exececutenonquery(),所以我相信您正在尝试更新产品表。

 sql = "UPDATE products set Quantity = (Quantity - @ItemBought) WHERE ProductCode = @ProductCode;"

        cmd = New MySqlCommand
        With cmd
            .Connection = conn
            .CommandText = sql
            .Parameters.Clear()

            .Parameters.AddWithValue("@ProductCode", formPOS.ProductCodeTB.Text)
            .Parameters.AddWithValue("@ItemBought", formInventory.quantityTB.Text)
            result = cmd.ExecuteNonQuery()
            If result = 0 Then
                MsgBox("Error in updating the selected product!")
            Else
                MsgBox("Successfully updated the selected product!")
            End If"

答案 2 :(得分:0)

得到正确的答案,我通过设置正确的TextBox和ProductCode列的Form来解决了这个问题

Try
        getConnection()

        sql = "UPDATE products SET Quantity = (Quantity - @ItemBought) WHERE ProductCode = @ProductCode;"

        cmd = New MySqlCommand
        With cmd
            .Connection = conn
            .CommandText = sql
            .Parameters.Clear()

            .Parameters.AddWithValue("@ProductCode", formPOS.ProductCodeTB.Text)
            .Parameters.AddWithValue("@ItemBought", formQuantity.quantityTB.Text)
            result = cmd.ExecuteNonQuery()
            If result = 0 Then
                MsgBox("Error in updating the selected product!")
            Else
                MsgBox("Successfully updated the selected product!")
            End If
        End With