开发者

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 au开发者_高级运维tocommit = 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...)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜