0

该字符串包含许多由空格分隔的单词,例如

employee_first_nm = "John Walker"

我想单独检索第一部分(“约翰”)。这部分我使用以下代码完成:

SUBSTR(employee_first_nm, 1, INSTR(employee_first_nm, ' '));

在某些情况下,字符串只有一个单词,例如“sonia”,这就是我遇到问题的地方。在这里,如果只有一个单词,该函数根本不会检索任何值。但我希望它在这种情况下获得完整的字符串,即“sonia”。

请帮忙

4

5 回答 5

4

Simply ensure there always will be a space;

... INSTR(employee_first_nm + ' ', ' ')

If there is already a space in the string then stuffing another one on the end makes no difference as the 1st one will be found, if there is no existing space adding one makes your logic work.

(Usually you also need to INSTR(..)-1 to strip the trailing space)

于 2012-07-09T14:10:58.580 回答
1
SUBSTR(employee_first_nm, 1, INSTR(CONCAT(employee_first_nm,' '), ' ')); 
于 2012-07-09T14:19:22.283 回答
0

或者,您可以检查 INSTR 是否返回正确的值:

(case when INSTR(employee_first_nm, ' ') > 0
      then SUBSTR(employee_first_nm, 1, INSTR(employee_first_nm, ' '))
      else employee_first_nm
 end)
于 2012-07-09T14:14:08.647 回答
0

为什么不在这里利用正则表达式的力量。

REGEXP_SUBSTR(employee_first_nm, '^[a-zA-Z]*\s?')

这应该返回您想要的子字符串。

于 2012-07-09T14:26:59.617 回答
-1

你可以试试:

SUBSTRING(select employee_first_nm,0, charindex(' ',employee_first_nm)

经测试:

select substring('John walker',0, charindex(' ','John walker more'))

返回 -> '约翰'

于 2012-07-09T14:13:25.423 回答