【问题标题】:How to check if the length of a string is more than one word and keep only the first word else keep the entire string in SQL?如何检查字符串的长度是否超过一个单词并仅保留第一个单词,否则将整个字符串保留在 SQL 中?
【发布时间】:2020-02-11 04:06:12
【问题描述】:

我在sql中有下表。

我只想保留名称列中的第一个单词。我已经编写了下面的代码,但是当我运行它时,它会提取比一个单词更长的字符串的第一个单词,但会为仅包含一个单词的字符串返回空单元格。你能告诉我我应该如何修改它以达到只保留所有字符串的第一个单词的预期结果。

SELECT ID,substr(Name, 1, instr ( Name, ' ' ) -1 ) AS Name FROM names_list

用于 Oracle 的 DBMS Toad

【问题讨论】:

    标签: sql oracle string-length


    【解决方案1】:

    这将从name 列中选择第一个单词:

    SQL> with names_list (id, name) as
      2    (select 1, 'John Smith'          from dual union all
      3     select 2, 'One'                 from dual union all
      4     select 3, 'Nikola O''Neil'      from dual union all
      5     select 4, 'Rose Ann Lee'        from dual union all
      6     select 5, 'Neil'                from dual union all
      7     select 6, 'William Hugh Forest' from dual union all
      8     select 7, 'Andrew'              from dual
      9    )
     10  select id,
     11    regexp_substr(name, '^\w+') name
     12  from names_list;
    
            ID NAME
    ---------- --------------------
             1 John
             2 One
             3 Nikola
             4 Rose
             5 Neil
             6 William
             7 Andrew
    
    7 rows selected.
    
    SQL>
    

    【讨论】:

      【解决方案2】:

      regexp_substr()怎么样?

      select regexp_substr(name, '^[^ ]+')
      from names_list;
      

      这比instr() 更灵活,因为您可以更好地控制分隔符。例如,如果有时也使用逗号:

      select regexp_substr(name, '^[^ ,]+')
      from names_list;
      

      【讨论】:

        猜你喜欢
        • 2021-03-07
        • 2011-05-22
        • 2017-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-19
        • 2012-05-20
        • 2020-03-22
        相关资源
        最近更新 更多