使用 SQL 服务器查找从特定字符到下一个 space 字符的子字符串

Find the sub string from specific character to the next space character using SQL Server

DECLARE @c varchar(100)
SET @c = 'This is and example #COIN-XXXX data only'

所以基本上,我想要从#COIN- 到 space 之后的所有内容,即(仅限 XXXX)。

我该如何解决?

一种方法是:

select left(v.str, charindex(' ', v.str) - 1)
from (select @c as str) x cross apply
     (values (stuff(x.str, 1, charindex('#COIN', x.str) + 5, ''))) v(str);

Here 是一个 db<>fiddle.

另一种方法是:

DECLARE @word varchar(max) = '#COIN-XXXX This is and example data only'
DECLARE @c varchar(100) = '#COIN1-'
DECLARE @CharIndex int = (select CHARINDEX(@c, @word))
if @CharIndex = 0
    select 'No matching word'
DECLARE @firstSpaceAfter_index int = (select CHARINDEX(' ', @word, @CharIndex))
if @firstSpaceAfter_index = 0
    set @firstSpaceAfter_index = len(@word) + 1

SELECT REPLACE(SUBSTRING(@WORD, @CharIndex, @firstSpaceAfter_index - @CharIndex),@c, '')