oracle - 将函数从 Oracle 转换为 PostgreSQL

标签 oracle postgresql database-migration plpgsql

我正在努力将某些东西从 Oracle 转换为 PostgreSQL。在Oracle文件中有一个函数:

instr(string,substring,starting point,nth location)

或者在我的文件中

instr(string,chr(10),instr(string,substring),1)

在 PostgreSQL 中这不存在,所以我查找了一个等效函数。我发现:

position(substring in string)

但是这个不允许起始位置和第n个位置参数。

有没有办法让这个函数从给定的点开始?或者在 PostgreSQL 中是否有更好的函数可以指定起始位置和第 n 个位置?

这必须在 PostgreSQL 8.2.15 上运行,因为这是我们在数据库上运行的版本。

最佳答案

Postgres 中的函数strpos(str, sub) 等同于Oracle 中的instr(str, sub)。不幸的是,该函数没有第三个和第四个参数,因此 Postgres 中的表达式必须更复杂。

substr(str, n) 函数从 n 位置开始给出 str 的子串。

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

由于instr()是一个强大的函数,我根据自己的需要在plpgsql中编写了它。

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

一些检查(来自 OLAP DML Functions 的例子):

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

Postgres 8.2 中没有reverse() 函数。你可以使用这个:

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

关于oracle - 将函数从 Oracle 转换为 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31059437/

相关文章:

oracle - 计算两个选择计数的百分比

oracle - 对 PUBLIC 数据库链接表的托管 ODP.NET 调用导致 TNS 错误

mysql - 仅用 1 个请求替代 2 个 SQL/ORACLE 请求

json - 在 Postgres 中使用嵌套数组高效查询 JSON

image - 在 Laravel 中存储照片。迁移文件的结构

mysql - Phinx 和 pt-online-schema-change

linux - libaio.so.1 : cannot open shared object file

python - Django 中从 sqlite 迁移到 postgresql

mysql - MySQL 仍然是免费/开源数据库的不错选择吗?

mysql - Laravel 5.5 - 迁移不起作用