Oracle 使用拼接字符串更新表


  1. //数据   
  2. ta   
  3. col_1 col_2   
  4. -----------   
  5. a   
  6. b   
  7. c   
  8. d   
  9. //结果:   
  10. col_1 col_2   
  11. -----------   
  12. a     z0001   
  13. b     z0002   
  14. c     z0003   
  15. d     z0004   
  16. //   
  17. create table ta(   
  18.        col_1 varchar2(2),   
  19.        col_2 varchar2(7))   
  20. /   
  21. insert into ta   
  22. select 'a','' from dual union all   
  23. select 'b','' from dual union all   
  24. select 'c','' from dual union all   
  25. select 'd','' from dual   
  26. /   
  27. //解法一:   
  28. declare   
  29.        rn number :=0;   
  30. begin   
  31.      for cl in (select col_1 from ta order by col_1) loop   
  32.          rn :=rn+1;   
  33.          update ta   
  34.          set col_2='z'||lpad(rn,4,'0')   
  35.          where col_1=cl.col_1;   
  36.          commit;   
  37.      end loop;   
  38. end;   
  39. /   
  40. //将表还原为原来的状态:   
  41. update ta   
  42. set col_2=''  
  43. where col_1 in ('a','b','c','d');//col_1 is not null;   
  44. //解法二:   
  45. begin   
  46.       for c in (select rowid rid,   
  47.                        row_number() over (order by col_1) rn   
  48.                 from ta)   
  49.       loop   
  50.           update ta   
  51.           set col_2='z000'||c.rn   
  52.           where rowid=c.rid;   
  53.       end loop;   
  54.       commit;   
  55. end;   
  56. /   
  57. //解法三:   
  58. create table tb as  
  59. select * from ta where 1=0   
  60. /   
  61. insert into tb   
  62. select col_1,'z000'||rn   
  63. from (   
  64.      select rownum rn,ta.col_1 col_1   
  65.      from ta)   
  66. /  

相关内容