我的SQL事务将1000个帐户从一个帐户转移到另一个帐户(名称,余额)?
我写下面的查询,我不知道如何检查条件。START TRANSACTION
UPDATE account SET balance = balance - 100 WHERE name = 'D'
UPDATE account SET balance = balance + 100 WHERE name = 'A'
COMMIT
如何在转移前检查足够数量的条件?
答案 0 :(得分:3)
使用存储过程来定义事务:
DELIMITER $$
DROP PROCEDURE IF EXISTS sample_balance_transfer $$
CREATE PROCEDURE sample_balance_transfer ()
BEGIN
DECLARE balance_var INT DEFAULT 0;
SELECT IFNULL(balance,0)
INTO balance_var
FROM account
WHERE name = 'D';
IF balance_var >= 1000 THEN
START TRANSACTION;
UPDATE account
SET balance = balance - 1000
WHERE name = 'D';
UPDATE account
SET balance = balance + 1000
WHERE name = 'A';
COMMIT;
END IF;
END $$
DELIMITER ;
然后执行存储过程:
CALL sample_balance_transfer();
注意 - 可能希望为错误添加退出处理程序