在事务中写入 IF 语句时出现错误

问题描述 投票:0回答:1
/*1. **Basic Transaction:**
   - Imagine you are working on a banking system. Write a transaction that transfers 
   $100 from account A to account B. Ensure the transaction is atomic.*/
   start transaction;
 
 -- saving the account balance before transaction
 
 set @old_account_balance = (select sum(account_balance) from account_balance_details 
 where account_number = "a" or account_number = "b");

-- updating the account balance

 update account_balance_details
 set account_balance = account_balance-100
 where account_number = "a";
   
update account_balance_details
set account_balance = account_balance+100
where account_number = "b";

set @new_account_balance = (select sum(account_balance) from account_balance_details
where account_number = "a" or account_number = "b");
   
if @new_account_balance = @old_account_balance
then
    commit;
else 
    rollback;
end if;

我收到类似预期更改、开始等错误,如何解决此问题?

sql mysql if-statement tcl alter
1个回答
0
投票

使用一个可靠的 UPDATE 查询:

UPDATE account_balance_details
SET account_balance = CASE account_number 
                      WHEN 'a' THEN account_balance-100
                      WHEN 'b' THEN account_balance+100
                      END
WHERE account_number IN ('a','b');

交易中不需要检查新旧余额。

© www.soinside.com 2019 - 2024. All rights reserved.