sql更新查询

时间:2012-06-11 05:43:39

标签: sql oracle

我想在_列中删除所有name前缀,但结果可能会导致冲突。因此,如果结果与现有结果重复,我希望为其添加_后缀,直到没有重复。

在下面的示例中,_test应重命名为test___

create table A  
(  
  name  VARCHAR2(20) unique,  
  id int  
);  
insert into a (name, id) values ('_test', 1);  
insert into a (name, id) values ('test', 2);  
insert into a (name, id) values ('test_', 3);  
insert into a (name, id) values ('test__', 4);  

1 个答案:

答案 0 :(得分:5)

试试这个:

merge into A
using (with aa as (select id, trim('_' from name) name from A)
     select rpad(name,
               length(name) - 1 + row_number()
               over(partition by name order by id),
               '_') name2,
          id
     from AA) s
on (s.id = a.id)
when matched then
  update set a.name = s.name2