DELIMITER $$
CREATE DEFINER=`pordenonelegge_it`@`localhost` PROCEDURE `sp_allinea_editori_2026`()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE db_name VARCHAR(128);

    DECLARE db_cursor CURSOR FOR
        SELECT schema_name
        FROM information_schema.schemata
        WHERE schema_name LIKE 'pordenonelegge_it_2026%'
        ORDER BY schema_name;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    -- 1) prendo il primo schema come modello
    SELECT schema_name INTO db_name
    FROM information_schema.schemata
    WHERE schema_name LIKE 'pordenonelegge_it_2026%'
    ORDER BY schema_name
    LIMIT 1;

    -- 2) creo la tabella common se non esiste
    IF db_name IS NOT NULL THEN
        SET @create_sql = CONCAT(
            'CREATE TABLE IF NOT EXISTS `pnlegge_common`.`tbl_editori` LIKE `',
            REPLACE(db_name,'`','``'),
            '`.`tbl_editori`'
        );
        PREPARE stmt FROM @create_sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;

    OPEN db_cursor;

    read_loop: LOOP
        FETCH db_cursor INTO db_name;
        IF done = 1 THEN
            LEAVE read_loop;
        END IF;


        PREPARE stmt FROM @copy_to_common;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;


        PREPARE stmt FROM @copy_to_db;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END LOOP;

    CLOSE db_cursor;
END$$
DELIMITER ;