更新行而不考虑两个单词之间的空格

时间:2014-02-12 07:29:41

标签: oracle sql-update sql-like

我希望将Text列中的文字替换为format(A,B),其中文字仅包含A和B,并忽略A和B之间的空格。

这是测试数据

Id   Text
1    A    B               //should be replaced with format(A,B).
2    A         B          //should be replaced with format(A,B).
3    A B                  //should be replaced with format(A,B).
4    A 1    B             //shouldn't be replaced.
5    A   B 1              //should be replaced with format(A,B) 1.

我想我必须做一些像

这样的事情
UPDATE test SET text = REPLACE(text, 'A[wild char for space]B', 'format(A,B)');

但我应该如何比较空间呢?像%会比较一切。

3 个答案:

答案 0 :(得分:0)

您可以将Oracle Regex用于此 Oracle Regex

答案 1 :(得分:0)

只是一个提示:

SQL> with t as (
  2  select 'A    B' col from dual union all
  3  select 'A              B' from dual union all
  4  select 'A B' from dual union all
  5  select 'AB' from dual union all
  6  select 'A 1  B' from dual union all
  7  select 'A   B 1' from dual
  8  )
  9  select regexp_replace(t.col, 'A[[:space:]]*B', 'format(A,B)') from t
 10  /

REGEXP_REPLACE(T.COL,'A[[:SPACE:]]*B','FORMAT(A,B)')                            
--------------------------------------------------------------------------------
format(A,B)                                                                     
format(A,B)                                                                     
format(A,B)                                                                     
format(A,B)                                                                     
A 1  B                                                                          
format(A,B) 1   

答案 2 :(得分:0)

适用于您的方案的SQL:

with tab(Id,Text) as 
(select 1,'A    B'   from dual union all --            //should be replaced with format(A,B).
select 2,'B         C' from dual union all --          //should be replaced with format(A,B).
select 3,'A B' from dual union all --                 //should be replaced with format(A,B).
select 4,'A 2    B' from dual union all --            //shouldn't be replaced.
select 5,'Y   Z 1' from dual) --             //should be replaced with format(A,B) 1.
select id, 
       text, 
       regexp_replace(text, '^\D\s+\D', 'format('||regexp_substr(text, '\D')||','||trim(regexp_substr(text, '\D+', 2))||')') format
  from tab;

输出:

| ID |        TEXT |        FORMAT |
|----|-------------|---------------|
|  1 |      A    B |   format(A,B) |
|  2 | B         C |   format(B,C) |
|  3 |         A B |   format(A,B) |
|  4 |    A 2    B |      A 2    B |
|  5 |     Y   Z 1 | format(Y,Z) 1 |

更新声明变为

UPDATE test SET text = regexp_replace(text, '^\D\s+\D', 'format('||regexp_substr(text, '\D')||','||trim(regexp_substr(text, '\D+', 2))||')');