Oracle sql to pgsql with table()函数问题

时间:2017-08-31 12:14:19

标签: sql postgresql split

我正在从Oracle迁移到pgsql,我就像下面这样的oracle sql:

select code,product_no,qty qty from t_ma_tb_inventory 
                    where code is not null and status=2
                    and update_type in (select * from table(splitstr(:types,',')))
                    and tb_shop_id=:shopId 
                     order by update_time

和splitstr函数如下:

  CREATE OR REPLACE FUNCTION splitstr (p_string text, p_delimiter text) RETURNS SETOF STR_SPLIT AS $body$
    DECLARE

        v_length   bigint := LENGTH(p_string);
        v_start    bigint := 1;
        v_index    bigint;

    BEGIN
        WHILE(v_start <= v_length)
        LOOP
            v_index := INSTR(p_string, p_delimiter, v_start);

            IF v_index = 0
            THEN
                RETURN NEXT SUBSTR(p_string, v_start);
                v_start := v_length + 1;
            ELSE
                RETURN NEXT SUBSTR(p_string, v_start, v_index - v_start);
                v_start := v_index + 1;
            END IF;
        END LOOP;

        RETURN;
    END
    $body$
    LANGUAGE PLPGSQL
    SECURITY DEFINER
    ;

-- REVOKE ALL ON FUNCTION splitstr (p_string text, p_delimiter text) FROM PUBLIC;

有人可以帮我写pgsql中的等效代码吗?非常感谢

1 个答案:

答案 0 :(得分:0)

您不需要编写自己的函数 - Postgres已经具有内置函数:string_to_array

select code, product_no, qty qty 
from t_ma_tb_inventory 
where code is not null and status=2
  and update_type = any ( string_to_array(:types,',') )
  and tb_shop_id = :shopId 
order by update_time;

如果要传递文本,但需要将其与整数进行比较,则需要强制转换结果数组:

select code, product_no, qty qty 
from t_ma_tb_inventory 
where code is not null and status=2
  and update_type = any ( string_to_array(:types,',')::int[] )
  and tb_shop_id = :shopId 
order by update_time;

但是:这是一个非常丑陋的解决方法,只有在Oracle中才需要,因为它不支持SQL中的实际数组(仅限PL / SQL)。

在Postgres中,直接传递一个整数数组(例如make :typesint[])会更好更多。然后不需要解析或转换:

select code, product_no, qty qty 
from t_ma_tb_inventory 
where code is not null and status=2
  and update_type = any ( :types )
  and tb_shop_id = :shopId 
order by update_time;