CREATE PROCEDURE stp_counterGetNextBlock(
    IN pYear INT,
    IN pName VARCHAR(100),
    IN pCount INT,
    OUT pStart INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Ritorna il prossimo valore di contatore per il flusso richiesto'
BEGIN
    DECLARE vOld INT;
    DECLARE vNew INT;

    -- Leggo il valore precedente (se esiste)
    SELECT Counter INTO vOld
    FROM utils_counter
    WHERE RefYear = pYear AND CountName = pName
    FOR UPDATE;

    IF vOld IS NULL THEN
        -- Primo inserimento
        SET vOld = 0;
        SET vNew = pCount;

        INSERT INTO utils_counter (RefYear, CountName, Counter)
        VALUES (pYear, pName, vNew)
        ON DUPLICATE KEY UPDATE Counter = VALUES(Counter);
    ELSE
        -- Incremento esistente
        SET vNew = vOld + pCount;

        UPDATE utils_counter
        SET Counter = vNew
        WHERE RefYear = pYear AND CountName = pName;
    END IF;

    -- pStart = primo valore del blocco
    SET pStart = vOld + 1;
END;