Oracle SQL判断字符串是不是在目标字符串中的函数

Oracle SQL判断字符串是否在目标字符串中的函数

根据需求,写了一段方法。

用于识别以下的情况:

判断 字符串A  在用逗号分隔的字符串B中是否存在

如:

v_str_a = aa ;

v_str_b= aa,bb,dd,cc ;

 

如上,就返回Y,否则返回N。

添加了一些校验。

 

以后可以根据需求,按照指定的分隔符,提取字符串。

毕竟Oracle的字符串解析比较麻烦,能封装就封装。

create or replace function func_str_inArray(p_target    varchar2,
                                            p_str_array varchar2)
  return varchar2 is

  v_flag        varchar2(1);
  v_comma_loc   int;
  v_cut_string  varchar2(300);
  v_rest_string varchar2(2000);
begin
  ------------------------
  --p_target 不能包含","!!!注意!!
  --info:这个函数用于识别目标字符串,是否在一串用“,”分开的字符串内
  ------------------------
  v_flag      := 'N';
  v_comma_loc := instr(p_str_array, ',');

  --如果是对比字符串是空,则返回false
  if nvl(p_str_array, '') = '' then
    return 'N';
  end if;
  --如果没有逗号,直接比较
  if length(p_str_array) > 0 and v_comma_loc = 0 then
    if p_target = p_str_array then
      return 'Y';
    else
      return 'N';
    end if;
  end if;

  v_rest_string := p_str_array;

  while v_comma_loc > 0 loop
    v_cut_string  := substr(v_rest_string, 0, v_comma_loc - 1);
    v_rest_string := substr(v_rest_string,
                            v_comma_loc + 1,
                            length(v_rest_string) - 1);
  
    if p_target = v_cut_string then
      v_flag := 'Y';
    end if;
  
    v_comma_loc := instr(v_rest_string, ',');
  
    if v_comma_loc = 0 and length(v_rest_string) > 0 then
      if p_target = v_rest_string then
        v_flag := 'Y';
      end if;
    end if;
  
  end loop;

  return v_flag;

end;

 

 

 

 

 

 

 

1 楼 flashtony 2013-01-18  
我的思路就是字符串前后加上',',进行比较 

select decode(sign(instr(',aa,bb,cc,',',aa,')),1,'Y','N') from dual;

以上须测试,仅供参考
2 楼 dacoolbaby 2013-01-18  
flashtony 写道
我的思路就是字符串前后加上',',进行比较 

select decode(sign(instr(',aa,bb,cc,',',aa,')),1,'Y','N') from dual;

以上须测试,仅供参考


恩,我测试过了。
觉得你的方法更好。
对比2边的字符串,都加上','后,基本就能够定位的很准确了。

甘拜下风~~