PL SQL用逗号分隔的字符串创建数字数组

时间:2016-06-17 08:36:59

标签: oracle plsql

我有一串用逗号分隔的数字,如'7845,6986,2548' 我想拆分逗号并将结果传递给select语句的IN子句 我曾经使用过这个功能:

create or replace TYPE t_in_list_tab as table of varchar2(4000);

create or replace FUNCTION in_list (p_in_list  IN  VARCHAR2) 
 RETURN t_in_list_tab
AS
  l_tab   t_in_list_tab := t_in_list_tab();
  l_text  VARCHAR2(32767) := p_in_list || ',';
  l_idx   NUMBER;
BEGIN
  LOOP
    l_idx := INSTR(l_text, ',');
    EXIT WHEN NVL(l_idx, 0) = 0;
    l_tab.extend;
    l_tab(l_tab.last) := TRIM(SUBSTR(l_text, 1, l_idx - 1));
    l_text := SUBSTR(l_text, l_idx + 1);
  END LOOP;

  RETURN l_tab;
END;

这个函数的返回类型是varchar2,但是我的列类型是数字,我尝试使用TO_NUMBER,如:

select * from my_tbl where col1 IN (TO_NUMBER(select * from table(IN_LIST('7845,6986,2548'))));

但它不起作用, 有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要将table collection expression(名为column_value)中的列放在to_number()来电中:

select to_number(column_value) from table(IN_LIST('7845,6986,2548')

演示:

with my_tbl(col1, col2) as (
  select 7845, 'Test 1' from dual
  union all select 2548, 'Test 2' from dual
  union all select 9999, 'Test 3' from dual
)
select * from my_tbl where col1 IN (
  select to_number(column_value) from table(IN_LIST('7845,6986,2548'))
);

      COL1 COL2 
---------- ------
      7845 Test 1
      2548 Test 2

您也可以使用加入:

select my_tbl.*
from
(
    select * from table(IN_LIST('7845,6986,2548'))
) tmp
join my_tbl
on my_tbl.col1 = to_number(tmp.column_value);