仅在找到新记录时更新“ varchar2”列

时间:2019-02-05 09:54:09

标签: oracle

我正在尝试为我的项目开发简单的代码。

我应该在哪里更新表books.PUBLISHER。在PUBLISHER列中,我们已经有以下值'abc; pqr',我想用'pqr; xyz'更新它,因此我的预期输出将是'abc; pqr; xyz'

update books SET PUBLISHER = PUBLISHER || '; ' ||'pqr; xyz'
where id = 1 and PUBLISHER  NOT LIKE '%pqr; xyz%';

我的预期输出为'abc; pqr; xyz'

2 个答案:

答案 0 :(得分:1)

您当前的publisher值包含字符串pqr。您的要求表明您不想重复该值。通过添加您提议的解决方案,将复制pqr值。

您可以使用replace()来避免重复:

update books 
SET PUBLISHER = replace(PUBLISHER, 'pqr', 'pqr; xyz')
where id = 1 
and PUBLISHER  NOT LIKE '%pqr; xyz%';

这将用pqr; xyz出现在pqr列中的任何地方代替publisher

答案 1 :(得分:0)

以下更新语句应完成该工作:

update books b
   set publisher =
       (select listagg(publisher_part, '; ') within group(order by publisher_part)
          from (select regexp_substr(bb.publisher, '[a-z]+', 1, level) as publisher_part
                  from (select publisher from books where id = b.id) bb
                connect by regexp_substr(bb.publisher, '[a-z]+', 1, level) is not null
                union
                select 'lmn' as publisher_part --> your new "publisher" pattern
                  from dual))
 where id = 1; --> id to update

内部选择(select regexp...)将发布者列分散在单独的结果中

abc
pqr
xyz
...

此后,新值lmnunion select from dual添加,最​​后结果由listagg以以前的格式聚合。

如APC所建议的,更好的解决方案是对表进行规范化。