计算字符串中的空格数

Jon*_*Way 3 sql t-sql sql-server

我正在进行数据验证,我正在尝试计算字符串中的空格数.我的问题是,当我计算空格时,文本之间有多个空格的任何sting或任何带有尾随空格的字符串都不计算在内我没有运气就尝试了以下代码.每个代码给出不同的结果,但不是所需的输出

DECLARE @MyTbl TABLE (ID INT, Name VARCHAR(300))
INSERT INTO @MyTBL VALUES
(1, 'Alfreds Futterkiste'), -- 1 space
(2,'Mike James Ray  '),     -- 4 spaces 1 space between each text and 2 spaces after text
(3,'Hanari  Carnes'),       -- 2 spaces between text
(4,'James Michael')

-- 1
SELECT ID,
LEN(Name)-LEN(REPLACE(Name, ' ', '')) AS Count_Of_Spaces 
FROM  @MyTBL
-- 2
SELECT ID,
LEN(Name + ';')-LEN(REPLACE(Name,' ','')) AS Count_Of_Spaces2 
FROM  @MyTBL
-- 3
SELECT ID,
LEN(Name)-LEN(REPLACE(Name,' ', '')) AS Count_Of_Spaces3  
FROM  @MyTBL
Run Code Online (Sandbox Code Playgroud)

基于第一个查询的当前输出

 ID Count_Of_Spaces
  1    1
  2    2
  3    2
  4    1
Run Code Online (Sandbox Code Playgroud)

期望的输出

 ID Count_Of_Spaces
 1     1
 2     4
 3     2
 4     1
Run Code Online (Sandbox Code Playgroud)

Luk*_*zda 12

你可以使用DATALENGTH:

SELECT ID,
DATALENGTH(Name)-LEN(REPLACE(Name,' ', '')) AS Count_Of_Spaces
FROM  @MyTBL;
Run Code Online (Sandbox Code Playgroud)

DBFiddle演示

LEN 不计算尾随空格.


如果NVARCHAR那时你需要除以2.

DECLARE @MyTbl TABLE (ID INT, Name NVARCHAR(300))
INSERT INTO @MyTBL VALUES
(1, 'Alfreds Futterkiste'), -- 1 space
(2,'Mike James Ray  '),     -- 4 spaces 1 space between 
                            -- each text and 2 spaces after text
(3,'Hanari  Carnes'),       -- 2 spaces between text
(4,'James Michael');

SELECT ID,
DATALENGTH(Name)/2-LEN(REPLACE(Name,' ', '')) AS Count_Of_Spaces
FROM  @MyTBL;
Run Code Online (Sandbox Code Playgroud)

DBFiddle Demo2