简体   繁体   中英

MySQL Trigger that requires a field from a previous event

I have another trigger question, before i explain, i'm gonna show you a code:

DELIMITER $$

CREATE PROCEDURE transferFunds ( receiver INT, sender INT, amount FLOAT )

BEGIN

  DECLARE senderBalance FLOAT;
  DECLARE receiverBalance FLOAT;

  SELECT balance INTO senderBalance 
    FROM accounts 
   WHERE accountNumber = sender;

  SELECT balance INTO receiverBalance 
    FROM accounts 
   WHERE accountNumber = receiver;

  SET autocommit = 0;

  UPDATE accounts
     SET balance = senderBalance - amount
   WHERE accountNumber = sender;

  UPDATE accounts
     SET balance = receiverBalance + amount
   WHERE accountNumber = receiver;

  IF senderBalance < amount THEN
    ROLLBACK;
  ELSE
    COMMIT;
  END IF;

END$$

CREATE TRIGGER transferTrigger AFTER UPDATE ON accounts
FOR EACH ROW
BEGIN

  -- Insert the Receiver and Sender and Amount to transfer_log table

END$$

I wanted to create a Trigger that would record the transfer that just happened, but I can't because Trigger works in a per row Event. How would I do that if I want to record the transfer event in a transfer_log table and insert the To and From account numbers and the amount that was transferred?

As you stated in your question, triggers work on a per row basis.

You should do the logging in your stored procedure directly. However you could use a workaround, though i do not think its safe - specially when dealing with money transactions (as shown in the OP).

Inside your stored proc:

SET @TranSender = sender;
SET @TranReceiver = receiver;
...

And inside your trigger:

INSERT log_table(Sender, Receiver...)
VALUES (@TranSender , @TranReceiver...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM