Oracle 根据逗号分隔字符串 同时记录一波坑

  报表需要过滤掉不需要的数据,由于报表是根据零件编号来统计,需要过滤掉不合格品,只能根据关联的物料编码(零件编号)来过滤,只能通过not in来过滤,但是天真的我却用下面代码来当子查询:

b.part_no not in (select  replace(wm_concat(t.materielcode),',',''',''') from quality_check t where t.materielcode is not null)

  怎么都过滤不掉,这是因为IN 后不是字符串而是一个结果集:上面脚本查出的结果为第一种。

查询结果
一错误:
001,002,003,004 

二正确:
001
002
003
004

  所以需要把上面的查询结果分隔:

一、创建返回对象数据类型:

create or replace type mytype as table of varchar2(4000) 

  也可以为数字:

create or replace type mytype as table of number;

二、创建分隔函数

create function my_split(piv_str in varchar2, piv_delimiter in varchar2)  
  --piv_str 为字符串,piv_delimiter 为分隔符  
  return mytype is  
  j        int := 0;  
  i        int := 1;  
  len      int := 0;  
  len1     int := 0;  
  str      varchar2(4000);  
  my_split mytype := mytype();  
begin  
  len  := length(piv_str);  
  len1 := length(piv_delimiter);  
  while j < len loop  
    j := instr(piv_str, piv_delimiter, i);  
    if j = 0 then  
      j   := len;  
      str := substr(piv_str, i);  
      my_split.extend;  
      my_split(my_split.count) := str;  
      if i >= len then  
        exit;  
      end if;  
    else  
      str := substr(piv_str, i, j - i);  
      i   := j + len1;  
      my_split.extend;  
      my_split(my_split.count) := str;  
    end if;  
  end loop;  
  return my_split;  
end my_split;  

  三、完成sql:

select *
  from manu_taskinfo mt
 where mt.part_no not in
       (select column_value
          from table (select my_split(wm_concat(t.materielcode), ',')
                        from quality_check t
                       where t.materielcode is not null))

  

原文地址:https://www.cnblogs.com/echo-ling/p/7479308.html