Transferring “Money” between accountID in MySQL

我怕爱的太早我们不能终老 提交于 2021-02-17 03:27:26

问题


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 procedure. If I for example use Call transfer (20,'Test',3,5). Then I will transfer 20 dollars from accountID 3 to accountID 5 and write the message "Test" , which is what it should do.

At the moment it is however possible to send money between non-existing accounts and the amount can be <0 for the sending accountID, for example call transfer (20000000,'Test',34,54).

Does anyone know how I can solve these problems(amount has to be >=0 and only existing accountIDs can receive and send money)? The code I am using can be found below:

Creating the tables:

Create table Account 
(
AccountID int AUTO_INCREMENT primary key 
,amount decimal check (amount >= 0));

Create table Transfers 
(
TransfersID int AUTO_INCREMENT primary key
,amount decimal
,from_account_id int not null
,to_account_id int not null
,note varchar(50) not null
,datetime datetime not null
,Constraint from_account_key foreign key (from_account_id) references 
Accounts (id)
,Constraint to_account_key foreign key (to_account_id) references Accounts 
(id)
);

insert into accounts (id, amount) values (1, (rand()*100));
insert into accounts (id, amount) values (2, (rand()*100));

Creating the stored procedure:

delimiter //
create procedure transfer (amount int, note varchar(50), sending_account 
int, receiving_account int)
begin

start transaction;
update accounts as A
set A.amount = A.amount - amount
where A.AccountID = sending_account;

update accounts as A
set A.amount = A.amount + amount
where A.AccountID = receiving_account;

insert into transfers values 
(TransfersID, amount, sending_account, receiving_account, note, now());
commit work;

end //
delimiter ;

回答1:


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 ;


来源:https://stackoverflow.com/questions/48884501/transferring-money-between-accountid-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!