SET TERM ^ ;

CREATE OR ALTER procedure SPD_NCM_IBPTAX
as
declare variable UF varchar(2);
declare variable NCM_CODIGO varchar(15);
declare variable TIPO varchar(10);
declare variable COUNT_REG integer;
declare variable COUNT_AUX integer;
declare variable ID_AUX integer;
declare variable IDS varchar(500);
BEGIN
    FOR
        SELECT
            X.UF,
            X.CODIGO,
            X.COUNT_REG,
            X.IDS
        FROM (
            SELECT
                T.UF,
                T.CODIGO,
                COUNT(T.ID) AS COUNT_REG,
                LIST(T.ID) AS IDS
            FROM TBIBPTAX T
            GROUP BY 1, 2
        ) X
        WHERE X.COUNT_REG > 1
   INTO :UF, :NCM_CODIGO, :COUNT_REG, :IDS
   DO BEGIN

        IF(:COUNT_REG > 1) THEN
        BEGIN
            :COUNT_AUX = :COUNT_REG;

            WHILE(:COUNT_AUX >= 2)
            DO BEGIN
                :ID_AUX = CAST(FN_ARRAY(:IDS, :COUNT_AUX, ',') AS INTEGER);

                IF(:ID_AUX > 0) THEN
                BEGIN
                    DELETE FROM TBIBPTAX T WHERE T.UF = :UF AND T.ID = :ID_AUX;
                END
                
                :COUNT_AUX = :COUNT_AUX - 1;
            END

        END


   END

END
^

SET TERM ; ^

