sql >> Base de Datos >  >> RDS >> Oracle

Función de conversión de Oracle a PostgreSQL

La función strpos(str, sub) en Postgres es equivalente a instr(str, sub) en Oráculo. Desafortunadamente, la función no tiene parámetros tercero y cuarto, por lo que la expresión en Postgres debe ser más compleja.

La función substr(str, n) da una subcadena de str a partir de n posición.

instr(str, ch, instr(str, sub), 1);                               --oracle
strpos(substr(str, strpos(str, sub)), ch) + strpos(str, sub) - 1; --postgres

Como instr() es una función poderosa. La escribí en plpgsql para mis propias necesidades.

create or replace function instr(str text, sub text, startpos int = 1, occurrence int = 1)
returns int language plpgsql immutable
as $$
declare 
    tail text;
    shift int;
    pos int;
    i int;
begin
    shift:= 0;
    if startpos = 0 or occurrence <= 0 then
        return 0;
    end if;
    if startpos < 0 then
        str:= reverse(str);
        sub:= reverse(sub);
        pos:= -startpos;
    else
        pos:= startpos;
    end if;
    for i in 1..occurrence loop
        shift:= shift+ pos;
        tail:= substr(str, shift);
        pos:= strpos(tail, sub);
        if pos = 0 then
            return 0;
        end if;
    end loop;
    if startpos > 0 then
        return pos+ shift- 1;
    else
        return length(str)- length(sub)- pos- shift+ 3;
    end if;
end $$;

Algunas comprobaciones (Ejemplos de Funciones OLAP DML ):

select instr('Corporate Floor', 'or', 3, 2);  -- gives 14
select instr('Corporate Floor', 'or', -3, 2); -- gives 2

No hay reverse() función en Postgres 8.2. Puedes usar esto:

-- only for Postgres 8.4 or earlier!
create or replace function reverse(str text)
returns text language plpgsql immutable
as $$
declare
    i int;
    res text = '';
begin
    for i in 1..length(str) loop
        res:= substr(str, i, 1) || res;
    end loop;
    return res;
end $$;