2015-10-17 189 views
1

我正在寫一個C#應用程序,每次發佈該書時都會將數據庫中特定圖書的數量減少1。數量不斷減少,直到它以書籍數量的負值結束。從MySQL數據庫中減去數量而不會變爲負數

我想知道如何減去沒有達到負值的書籍數量。

下面是代碼:

connect = new SqlConnection(conStr.connectString); 
connect.Open(); 
string updateString = "update tblbooks set quantity=quantity - 1 where [email protected]_id"; 
cmd = new SqlCommand(updateString, connect); 

回答

0

只需使用一個casegreatest()

update tblbooks 
    set quantity = quantity - 1 
    where book_id = @book_id and quantity >= 1; 
0

用途:

update tblbooks 
    set quantity = greatest(quantity - 1, 0) 
    where book_id = @book_id; 

或者更好的是,在where使用條件在哪裏上課以確保你只更新那些有的記錄

update tblbooks 
set quantity=quantity - 1 
where quantity>0 and [email protected]_id