DROP TABLE IF EXISTS `autosearch_sended`;

CREATE TABLE `autosearch_sended` (
    `filter_id` INT(11) UNSIGNED NOT NULL COMMENT 'ИД фильтра' ,
    `object_id` INT(11) UNSIGNED NOT NULL COMMENT 'ИД объекта'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci COMMENT='Таблица отправленных объектов в автопоиске';

DROP PROCEDURE IF EXISTS autoSearchSended;

DELIMITER //
CREATE PROCEDURE autoSearchSended()
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE indx INTEGER DEFAULT 0;
    DECLARE filter_id VARCHAR(4000);
    DECLARE sended VARCHAR(4000);

    DECLARE currentFilter CURSOR FOR
        SELECT `autosearch_results`.`filter_id` AS 'filter_id',
            JSON_EXTRACT(REPLACE(`autosearch_results`.`sended`, '&quot;', ''), '$')
        FROM `autosearch_results`
        WHERE `autosearch_results`.`sended` != '' AND
            `autosearch_results`.`sended` IS NOT NULL AND
            `autosearch_results`.`sended` != 'null' AND
            `autosearch_results`.`sended` NOT LIKE '[]';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

OPEN currentFilter;

ALTER TABLE `autosearch_results` DROP `sended`;

getSended: LOOP
        FETCH currentFilter INTO filter_id, sended;
        IF finished = 1 THEN LEAVE getSended;
END IF;
        WHILE indx < JSON_LENGTH(sended) DO
SELECT `filter_id`, JSON_EXTRACT(sended, CONCAT('$[', indx, ']')) AS `object_id`;
INSERT INTO `autosearch_sended` (`filter_id`, `object_id`) VALUES (`filter_id`, JSON_EXTRACT(sended, CONCAT('$[', indx, ']')));
SET indx = indx + 1;
END WHILE;
        SET indx = 0;
END LOOP getSended;
CLOSE currentFilter;
END; //

DELIMITER ;

CALL autoSearchSended();
DROP PROCEDURE IF EXISTS autoSearchSended;