日期:2014-05-17  浏览次数:21341 次

oracle 查询结果中的一个字段结果是id的组合(1,2)是字符串,如何让另一个表查询的时候可以用in查这个Id的集合
.
今天在做一个报表的时候,想用一个sql查询最后结果,但在实现的时候遇到一点问题,我查到的一个字段是varchar型的,多个id的组合(如:1,2,3,并且这个结果是一个selete语句实现的),但是我要在另一个表中查询使用这个id,而这个id是int型的。所以,没办法直接使用这个结果,总会报错说无效的number类型。后面同事帮忙查到一个方法可以把这个结果转成对应的行的记录。

例:我查询的这个字段结果为3,4.

select replace(appr_or_reasons,'|',''',''')  from equ_odr_trade_ovr_request where id = 21748;

如下语句可以将这个值转成:

3

4


with temp as

(select '3,4' text from dual)

select regexp_substr(text,'[0-9]+',1,rn) text from temp t1,

(select level rn from dual connect by rownum <= (select length(text)-length(replace(text,',',''))+1 from temp)) t2


最后我便可以直接将上面语句放到in子句中。便可以查到数据

 select cor.credit_or_reason 
  from sds_credit_or_reason  cor 
  where id in(
   with temp as
(select (select replace(appr_or_reasons,'|',''',''')  from equ_odr_trade_ovr_request where id = 21748) id from dual)
select regexp_substr(id,'[0-9]+',1,rn) id from temp t1,
(select level rn from dual connect by rownum <= (select length(id)-length(replace(id,',',''))+1 from temp)) t2
  );


但感觉 这样很复杂,以后维护的人也看不懂,不知道大家有没有简单,或更好一点的方法 


------最佳解决方案--------------------
可以用动态sql,execute immedate,把sql拼接起来,例如
declare
ids varchar2(100) := '7369,7499';
type enamelist is table of emp.ename%type;
enames enamelist;
begin
execute immediate 'select ename from emp where empno in (' 
------其他解决方案--------------------
使用自定义分隔函数可以实现,网上有很多的
------其他解决方案--------------------
 ids 
------其他解决方案--------------------
 ')' bulk collect into enames;
FOR i IN 1..enames.COUNT() LOOP
dbms_output.put_line(enames(i));
END LOOP;
end;

------其他解决方案--------------------
用substr函数就行了