SQL字符串:计算字符串中的单词

sup*_*ser 2 sql-server string

我在这里搜索了很多问题,但我找到的所有答案都是针对不同的语言,如Javascript等.

我在SQL中有一个简单的任务,我似乎无法找到一个简单的方法.我只需要计算SQL字符串(句子)中"单词"的数量.您可以在我的示例中看到为什么"单词"在引号中."单词"由空格分隔.

例句:

1. I am not your father.
2. Where are your brother,sister,mother?
3. Where are your brother, sister and mother?
4. Who are     you?
Run Code Online (Sandbox Code Playgroud)

期望的答案:

1. 5
2. 4
3. 7
4. 3
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我需要计算忽略符号的"单词"(我必须将它们视为单词的一部分).所以样品没有.2: (1)Where (2)are (3)your (4)brother,sister,mother? = 4

我可以通过这样做替换来处理多个空格:
REPLACE(string, ' ', ' ') -> 2 whitespaces to 1 REPLACE(string, ' ', ' ') -> 3 whitespaces to 1 and so on..

我可以使用什么SQL函数来执行此操作?我使用SQL Server 2012但需要一个在SQL Server 2008中运行的功能.

Zoh*_*led 7

这是一种方法:

创建并填充样本表(在将来的问题中保存此步骤)

DECLARE @T AS TABLE
(
    id int identity(1,1),
    string varchar(100)
)

INSERT INTO @T VALUES
('I am not your father.'),
('Where are your brother,sister,mother?'),
('Where are your brother, sister and mother?'),
('Who are     you?')
Run Code Online (Sandbox Code Playgroud)

使用CTE来替代多个空格一个空格(感谢戈登·利诺夫的答案在这里)

;WITH CTE AS
(
SELECT  Id,
        REPLACE(REPLACE(REPLACE(string, ' ', '><' -- Note that there are 2 spaces here
                               ), '<>', ''
                       ), '><', ' '
                ) as string
FROM @T
)
Run Code Online (Sandbox Code Playgroud)

查询CTE - 字符串的长度 - 字符串的长度,不带空格+ 1:

SELECT id, LEN(string) - LEN(REPLACE(string, ' ', '')) + 1 as CountWords
FROM CTE 
Run Code Online (Sandbox Code Playgroud)

结果:

id  CountWords
1   5
2   4
3   7
4   3
Run Code Online (Sandbox Code Playgroud)