Transferring “Money” between accountID in MySQL

前端 未结 1 1505
自闭症患者
自闭症患者 2021-01-27 04:59

I have a question which I have tried to Google but haven\'t find an answer to yet. What I am trying to do is transferring money between two accounts in MySQL with a stored proce

1条回答
  •  孤城傲影
    2021-01-27 05:40

    Added a check for the amount at the beginning of the procedure, and moved insert into transfers before update statements. There are foreign keys in transfers table referencing account table, so if you try to insert id that does not exist it will fail immediately.

    delimiter //
    create procedure transfer (amount int, note varchar(50), sending_account 
    int, receiving_account int)
    this_proc:begin 
    
    start transaction;
    
    if amount <= 0 then
        leave this_proc;
    end if;
    
    insert into Transfers values 
    (TransfersID, amount, sending_account, receiving_account, note, now());
    
    update Account as A
    set A.amount = A.amount - amount
    where A.AccountID = sending_account;
    
    update Account as A
    set A.amount = A.amount + amount
    where A.AccountID = receiving_account;
    
    commit work;
    
    end //
    delimiter ;
    

    0 讨论(0)
提交回复
热议问题