create or replace FUNCTION GET_NEW_AUTO_ID(di VARCHAR2) RETURN NUMBER
IS
    nextnumber NUMBER(10);
    license varchar(4);
    COUNTER_EXISTS NUMBER(10);
BEGIN
    SELECT DI000001 into license FROM DT401 WHERE DI026548 = 1;
    IF di = '001400' THEN
        SELECT COUNT(*) INTO COUNTER_EXISTS FROM DT820 WHERE di008199 = '001400' AND DI008198 = license;
        IF COUNTER_EXISTS = 0 Then
            insert into dt820 (DI008198, DI008199, DI008202, DI008203,  DI008204, DI008205, DI008206, 
            				   DI008207, DI008208, DI008209, DI008210, DI008211, DI008212, DI008213)
                       values (license, '001400', SYSDATE, SYSDATE, 7, 'MIGRATION', 'MIGRATION', 
                       		   license, Null, 7, 7, 7, 1, 0);
            nextnumber := 1;           
        ELSE
            SELECT to_number(di008212)+1 INTO nextnumber FROM DT820 WHERE di008199 = '001400' AND DI008198 = license FOR UPDATE OF di008212;
        
        END IF;
        
        UPDATE dt820 SET di008212 = lpad(to_char(nextnumber),9,'0') WHERE di008199 = '001400' AND di008198 = license;
        RETURN nextnumber;
    END IF;
    RETURN NULL;
END;