Oracle:在文本字段中使用 IN 子句? [复制]

2023-12-10

可能的重复:
如何在 oracle 9i 中最好地分割 csv 字符串

我有一些遗留数据VARCHAR2(100) field SUBID具有逗号分隔的数据:

empno   subid
1       1, 3, 2
2       18,19, 3, 6, 9

etc.

我需要写相当于

select * 
  from table 
 where id in ( select SUBID from subidtable where empno = 1 )

Oracle 有没有办法实现这一点?

Edit:

添加了一些说明。我需要做IN子句针对单行(而不是所有行)存储在字符串中的值。


可以,但是有点难看。取决于Oracle版本

您可以使用以下变体这个 AskTom 线程将数据解析为集合并在 SQL 语句中使用该集合。这应该适用于自 8.1.5 以来的任何版本的 Oracle,但这些年来语法已经变得更简单了。

SQL> create or replace type myTableType as table
  2       of varchar2 (255);
  3  /

Type created.

SQL> ed
Wrote file afiedt.buf

  1  create or replace
  2       function in_list( p_string in varchar2 ) return myTableType
  3    as
  4        l_string        long default p_string || ',';
  5        l_data          myTableType := myTableType();
  6        n               number;
  7    begin
  8      loop
  9          exit when l_string is null;
 10          n := instr( l_string, ',' );
 11          l_data.extend;
 12          l_data(l_data.count) :=
 13                ltrim( rtrim( substr( l_string, 1, n-1 ) ) );
 14          l_string := substr( l_string, n+1 );
 15     end loop;
 16     return l_data;
 17*  end;
SQL> /

Function created.

SQL> select ename
  2    from emp
  3   where empno in (select column_value
  4                     from table( in_list( '7934, 7698, 7521' )));

ENAME
----------
WARD
BLAKE
MILLER

您还可以使用正则表达式,如中讨论的这个 StackOverflow 线程

SQL> ed
Wrote file afiedt.buf

  1  select ename
  2    from emp
  3   where empno in (select regexp_substr(str, '[^,]+',1,level)
  4                     from (select '7934, 7698, 7521' str from dual)
  5*                 connect by level <= regexp_count(str,'[^,]+'))
SQL> /

ENAME
----------
WARD
MILLER
BLAKE
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Oracle:在文本字段中使用 IN 子句? [复制] 的相关文章

随机推荐