MySQL “After Insert” Trigger keeps inserting nulls

后端 未结 2 1030
礼貌的吻别
礼貌的吻别 2021-01-28 03:31

I really hope someone can help me out with this as it\'s been bugging me for days. I have an after insert trigger on my users table that inserts a record into an audit table aft

相关标签:
2条回答
  • 2021-01-28 03:56

    Well, after creating different types of triggers and experimenting, i figured that the insert trigger might have been firing more than once for some reason, actually firing both insert and update triggers, and the last row always had nulls which was the only record being inserted. It's really strange. So anyway, to get around this i changed my code to this and it's working with no issues thus far:

    DELIMITER ^^
    
    CREATE TRIGGER UsersUpdate AFTER UPDATE ON users
    FOR EACH ROW
    BEGIN
    
    IF NEW.username IS NOT NULL THEN
    
    IF EXISTS (SELECT 1 FROM users_audit WHERE username = NEW.username) THEN
    UPDATE users_audit SET `username` = NEW.username,  `FirstName` = NEW.FirstName, `LastName` = NEW.LastName, `address` = NEW.address, `email` = NEW.email WHERE username = OLD.username;
    ELSE
    INSERT INTO users_audit (`username`, `FirstName`, `LastName`, `address`, `email`)
    VALUES (NEW.username, NEW.FirstName, NEW.LastName, NEW.address, NEW.email);
    END IF;
    
    END IF;
    
    END
    ^^
    
    0 讨论(0)
  • 2021-01-28 03:59

    Looks like a problem with web form. Check values which are inserted into Users table. Are they NULL?

    You may change INSERT statement in the trigger -

    INSERT INTO `users_audit` (`username`, `address`, `email`)
    VALUES (USER(), 'temp address', 'temp email');
    

    and sure that trigger works properly.

    0 讨论(0)
提交回复
热议问题