Oracle
 sql >> Teknologi Basis Data >  >> RDS >> Oracle

Mengonversi fungsi dari Oracle ke PostgreSQL

Fungsi strpos(str, sub) di Postgres setara dengan instr(str, sub) di Oracle. Sayangnya, fungsi tersebut tidak memiliki parameter ketiga dan keempat, sehingga ekspresi di Postgres harus lebih kompleks.

Fungsi substr(str, n) memberikan substring dari str mulai dari n posisi.

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

Sebagai instr() adalah fungsi yang kuat yang saya tulis di plpgsql untuk kebutuhan saya sendiri.

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 $$;

Beberapa pemeriksaan (Contoh dari Fungsi DML OLAP ):

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

Tidak ada reverse() fungsi di Postgres 8.2. Anda dapat menggunakan ini:

-- 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 $$;


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana saya bisa terhubung ke database Oracle berbasis web dengan Java?

  2. Bagaimana menangani hilangnya presisi pada tipe numerik JDBC karena fungsi pengelompokan

  3. Pernyataan SQL bergabung dengan Oracle dan MS SQL Server

  4. Cara menonaktifkan cache Oracle untuk tes kinerja

  5. Cara memanggil blok anonim pl/sql dari blok anonim pl/sql