USE partsltd_prod;

DROP TRIGGER IF EXISTS partsltd_prod.before_insert_PH_User_Change_Set;

DELIMITER //
CREATE TRIGGER partsltd_prod.before_insert_PH_User_Change_Set
BEFORE INSERT ON partsltd_prod.PH_User_Change_Set
FOR EACH ROW
BEGIN
	IF NEW.updated_last_on <=> NULL THEN
		SET NEW.updated_last_on = NOW();
	END IF;
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER partsltd_prod.before_update_PH_User_Change_Set
BEFORE UPDATE ON partsltd_prod.PH_User_Change_Set
FOR EACH ROW
BEGIN
	IF NOT EXISTS(SELECT * FROM partsltd_prod.PH_User WHERE id_user = NEW.id_user_updated_last_by) THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New Updated-Last-By User ID must be provided.';
	END IF;
END //
DELIMITER ;
