如何检查字符串的长度是否超过一个单词并仅保留第一个单词否则将整个字符串保留在 SQL 中?
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 中有以下 table。
我只想保留名称列中的第一个单词。我已经编写了下面的代码,但是当我 运行 它提取第一个单词的字符串比一个单词长,但 returns 空单元格的字符串只包含一个单词。你能告诉我我应该如何修改它以达到只保留所有字符串的第一个单词的预期结果吗?
SELECT ID,substr(Name, 1, instr ( Name, ' ' ) -1 ) AS Name FROM names_list
用于 Oracle 的 DBMS Toad
regexp_substr()
怎么样?
select regexp_substr(name, '^[^ ]+')
from names_list;
这比 instr()
更灵活,因为您可以更好地控制分隔符。例如,如果有时也使用逗号:
select regexp_substr(name, '^[^ ,]+')
from names_list;
这将 select 第一个 单词 来自 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>
我在 sql 中有以下 table。
我只想保留名称列中的第一个单词。我已经编写了下面的代码,但是当我 运行 它提取第一个单词的字符串比一个单词长,但 returns 空单元格的字符串只包含一个单词。你能告诉我我应该如何修改它以达到只保留所有字符串的第一个单词的预期结果吗?
SELECT ID,substr(Name, 1, instr ( Name, ' ' ) -1 ) AS Name FROM names_list
用于 Oracle 的 DBMS Toad
regexp_substr()
怎么样?
select regexp_substr(name, '^[^ ]+')
from names_list;
这比 instr()
更灵活,因为您可以更好地控制分隔符。例如,如果有时也使用逗号:
select regexp_substr(name, '^[^ ,]+')
from names_list;
这将 select 第一个 单词 来自 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>