SQL - 大写忽略大写字母的每个单词

时间:2018-01-10 16:06:43

标签: sql oracle

我需要能够转换像

这样的东西
'ABC abc abc Abc' 

'ABC Abc Abc Abc' 

所以每个单词的第一个字母都成为大写字母,有大写字母的单词保持不变。

我已经尝试了initcap但是在将每个单词的其余部分大写后,它会变为小写。

select initcap('ABC abc abc Abc') from dual; 

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是一个选项:

SQL> with
  2  test as
  3    (select 'ABC abc abc Abc' col from dual),
  4  tor as
  5    -- convert COL into rows
  6    (select regexp_substr(col, '[^ ]+', 1, level) val
  7     from test
  8     connect by level <= regexp_count(col, ' ') + 1),
  9  capit as
 10    -- choose whether to capitalize first letter or not
 11    (select case when upper(val) = val then val
 12                 else initcap(val)
 13            end cap
 14     from tor)
 15  -- concatenate them back to a string
 16  select listagg(cap, ' ') within group (order by null) result
 17  from capit;

RESULT
--------------------------------------------------------------------------------
ABC Abc Abc Abc

SQL>

或者,稍作修改:

SQL> with
  2  test as
  3    (select 'ABC abc abc Abc' col from dual)
  4  select listagg(
  5         case when         regexp_substr(col, '\w+', 1, level) =
  6                   upper(  regexp_substr(col, '\w+', 1, level))
  7              then         regexp_substr(col, '\w+', 1, level)
  8              else initcap(regexp_substr(col, '\w+', 1, level))
  9         end, ' ') within group (order by null) res
 10  from test
 11  connect by level <= regexp_count(col, ' ') + 1;

RES
-----------------------------------------------------------------------
ABC Abc Abc Abc

SQL>