ORCLE中例如1.11.123排序

create or replace function num_sort(str varchar2) return varchar2 is
  v_s varchar2(50);
  i number;--存储获取的位置
  j number;--循环的重要变量
  x number;--存储第二个特殊字符的位置
  y varchar2(50);--接收判断是否大于10
begin
  j := 0;
  x := 0;
  v_s := '';
  select nvl(length(translate(str, 'a0123456789', ' ')),-1) into i from dual;
  if (str is null) then--最顶级
     v_s := '00';
  elsif (str is not null and i=-1) then--第二级
     if str<10 then--1位数字,补0再屏贴
         v_s := '0' || str;
     else
         v_s :=  str;
     end if;
  end if;
  while i > 0 loop
    j := j + 1;
    if (j=1) then--第一个
       select substr(str,1,INSTR(str,'.',1,1)) into y from dual;
       if y<10 then--1位数字,补0再屏贴
         v_s := v_s || '0' || y;
       else
         v_s := v_s || y;
       end if;
    end if;
    if (i>1) then--中间  i>1说明还没有结束,如果只有一个特殊字符,那么只会循环一次,且不会进入中间
        select INSTR(str,'.',1,j+1)-INSTR(str,'.',1,j) into x  from dual;
        if (x = 2) then--1位数字,补0再屏贴
           select substr(str,INSTR(str,'.',1,j)+1,1) into y  from dual;
        elsif (x = 3) then --2位数字,补0再屏贴
           select substr(str,INSTR(str,'.',1,j)+1,2) into y  from dual;
        end if;
    elsif (i=1) then--取最后一个
       select substr(str,INSTR(str,'.',1,j)+1,3) into y from dual;
    end if;
    --每次循环的时候,取特殊字符 . 对应的字符串是否小于10,
    --如果小于,使用0进行补充并组合在一个字符串中
    if y<10 then--1位数字,补0再屏贴
         v_s := v_s || '00' || y;
       elsif y<100 then
         v_s := v_s || '0' || y;
       else
         v_s := v_s || y;
       end if;
    i := i - 1;--每次减一,循环的条件
  end loop;
  return v_s;
end num_sort;

猜你喜欢

转载自awen7916.iteye.com/blog/2199853