0

I have a column name 'balance' & 'status'. I got the Qty from users input.
What I want to perform is update balance (balance-qty)
and after updating balance if balance is 0 then I want to change status to 2.
Is it possible to perform these 2 operations in one query?

Thanks in advance.

John Woo
  • 258,903
  • 69
  • 498
  • 492
user1084885
  • 77
  • 1
  • 1
  • 6

2 Answers2

1

Yes, you can do that it one query, all need need to do is to use InLine IF statement.

UPDATE tableName
SET balance = balance - qty,
    status = IF(balance - qty = 0, 2, status)
// WHERE condition here (if any)...

and since you have mentioned that the Qty came from the user, please take a look at the article below to learn how to prevent from SQL Injection. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • thanks, it works with little change. I modified if statement status=IF(balance=0,2,status). I guess balance=balance-qty perform first and if statement. – user1084885 Jan 04 '13 at 18:26
  • user input is forced to be numeric, so no need to worry about SQL Injection – user1084885 Jan 04 '13 at 18:35
0

Yes; you can write something like:

UPDATE ...
   SET balance = ...,
       status = CASE WHEN ... = 0 THEN 2 ELSE status END
 WHERE ...
;
ruakh
  • 175,680
  • 26
  • 273
  • 307