我的表格如下:
HarvestID | CheckIn | Actual | Status
1 | Date | 100 | Process
2 | Date | 200 | Process
3 | Date | 400 | Process
我的问题是如果我设置Qty ='350'然后更新ID'1'和& '2'为0,ID'3'数量='350'
有没有一种方法可以做到这一点,而无需创建一个新表来存储'A'数量的总和并使用存储过程?
我尝试的是:
cmdTemp = New MySqlCommand("SELECT * FROM tb_harvest ORDER BY CheckIn ASC LIMIT 1", cn)
sqlrd = cmdTemp.ExecuteReader
While sqlrd.Read
harvestid = sqlrd("HarvestID")
qtyTemp1 = sqlrd("Actual") - Qty : qtyTemp2 = sqlrd("Actual")
End While
sqlrd.Close()
If qtyTemp1 < 0 Then
cmdTemp = New MySqlCommand("UPDATE tb_harvest SET Actual=0 WHERE HarvestID=" & harvestid & "; " & _
"UPDATE tb_harvest SET Actual=Actual+" & qtyTemp1 & " WHERE HarvestID=" & harvestid + 1, cn)
cmdTemp.ExecuteNonQuery()
Else
cmdTemp = New MySqlCommand("UPDATE tb_harvest SET Actual=Actual-" & qtyTemp2 & " WHERE HarvestID=" & harvestid, cn)
cmdTemp.ExecuteNonQuery()
End If
答案 0 :(得分:0)
您可以使用变量执行此操作:
set @qty = 350;
update tb_harvest
set actual = (case when @qty <= 0 then 0
when @qty >= actual
then if(@qty := @qty - actual, 0, 0)
when (@tmp := actual - @qty),
then if(@qty := 0, @tmp, @tmp)
else actual -- should never happen
end)
order by harvestid;