有一个表中的某个字段,其值是以“##”分隔的字符串,如“##AAA##BB”、“##AA”、“##AA##CC##DD”,我想在Select 是只取出这个字段的最后一个“##”后面的内容,即上述三条记录中的“##BB”  “##AA”  “##DD”,这个语句要怎么写?

解决方案 »

  1.   

    试试这个
    SELECT  substr('#####AAA##BB', INSTR('#####AAA##BB', '##', -1, 1)) "Instring" FROM DUAL;
      

  2.   

    select substr('#####AAA##BB',instr('#####AAA##BB','##',-1,1)+2) from dual;
      

  3.   


    也可以把上面的功能写成一个function如下SQL>
    create or replace function convert2(str1 in varchar2)  return varchar2 is
    v_result varchar2(4000);
    begin
    v_result := SUBSTR(str1, INSTR(str1, '##', -1, 1));
    return v_result;
      
    end convert2;
    /
    函数已创建。SQL> select convert2('####DDD##VV') from dual;
    CONVERT2('####DDD##VV')
    --------------------------------------------------
    ##VV
    SQL> select convert2('####DDDVV') from dual;
    CONVERT2('####DDDVV')
    ------------------------------------------------
    ##DDDVV
    SQL> select convert2('AA##D##BB#DDDVV') from dual;
    CONVERT2('AA##D##BB#DDDVV')
    ---------------------------------------------------
    ##BB#DDDVV
    SQL> select convert2('#DD#DD#DD#DDDVV') from dual;(如果不匹配,返回原值)
    CONVERT2('#DD#DD#DD#DDDVV')
    ---------------------------------------------------
    #DD#DD#DD#DDDVV
      

  4.   

    和长度没有关系,LZ看看instr函数的具体用法:
    对于instr函数,我们经常这样使用:从一个字符串中查找指定子串的位置。例如:
    SQL> select instr('yuechaotianyuechao','ao') position from dual;
     
      POSITION
    ----------
             6
     
    从字符串'yuechaotianyuechao'的第一个位置开始,向后查找第一个出现子串'ao'出现的位置。
     
    其实instr共有4个参数,格式为“instr(string, substring, position, occurrence)”。可实现子串的如下搜索:
    1.从指定位置开始搜索子串
    2.指定搜索第几次出现的子串的位置
    3.从后向前搜索
     
    --1.从第7个字符开始搜索
    SQL> select instr('yuechaotianyuechao','ao', 7) position from dual;
     
      POSITION
    ----------
            17
     
    --2.从第1个字符开始,搜索第2次出现子串的位置
    SQL> select instr('yuechaotianyuechao','ao', 1, 2) position from dual;
     
      POSITION
    ----------
            17
    --3.从倒数第1个字符开始,搜索第1次出现子串的位置
    SQL> select instr('yuechaotianyuechao','ao', -1, 1) position from dual;
     
      POSITION
    ----------
            17
     
    --3.从倒数第1个字符开始,搜索第2次出现子串的位置
    SQL> select instr('yuechaotianyuechao','ao', -1, 2) position from dual;
     
      POSITION
    ----------
             6