我正在编写一个C#应用程序,每次发布本书时,它会将数据库中特定书籍的数量减少1。数量不断减去,直到最终以负值作为账面数量。
我想知道如何在不达到负值的情况下减去图书数量。
以下是代码:
R[0,0]
答案 0 :(得分:0)
只需使用case
或greatest()
:
update tblbooks
set quantity = greatest(quantity - 1, 0)
where book_id = @book_id;
或者,更好的是,使用where
中的条件:
update tblbooks
set quantity = quantity - 1
where book_id = @book_id and quantity >= 1;
答案 1 :(得分:0)
在class中使用以确保仅更新具有quantity > 0
update tblbooks
set quantity=quantity - 1
where quantity>0 and book_id=@book_id