我有一个问题,我曾试过谷歌,但尚未找到答案。我想要做的是使用存储过程在MySQL中的两个帐户之间转移资金。例如,如果我使用呼叫转移(20,'测试',3,5)。然后我将从accountID 3转移20美元到accountID 5并写下消息“Test”,这是应该做的。
然而,此时可以在不存在的帐户之间汇款,并且对于发送帐户ID,金额可以是<0,例如呼叫转移(20000000,'测试',34,54)。
有谁知道如何解决这些问题(金额必须> = 0且只有现有的帐户ID可以接收和汇款)?我正在使用的代码可以在下面找到:
创建表格:
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));
创建存储过程:
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 ;
答案 0 :(得分:0)
在过程开始时添加了对金额的检查,并在insert into transfers
语句之前移动了update
。 transfers
表引用account
表中有外键,因此如果您尝试插入不存在的id
,它将立即失败。
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 ;