我正在进行数据验证,我正在尝试计算字符串中的空格数。我的问题是,当我计算空格时,文本之间有多个空格的任何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
基于第一个查询的当前输出
ID Count_Of_Spaces
1 1
2 2
3 2
4 1
期望的输出
ID Count_Of_Spaces
1 1
2 4
3 2
4 1
答案 0 :(得分:12)
您可以使用DATALENGTH
:
SELECT ID,
DATALENGTH(Name)-LEN(REPLACE(Name,' ', '')) AS Count_Of_Spaces
FROM @MyTBL;
<强> DBFiddle Demo 强>
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;
<强> DBFiddle Demo2 强>
答案 1 :(得分:1)
你在尝试#2时得到了答案。可能只是没有意识到在查询的第二部分(REPLACE
)中进行追加
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')
-- 2
SELECT ID,
LEN(';' + Name + ';')-LEN(REPLACE(';' + Name + ';',' ','')) AS Count_Of_Spaces2
FROM @MyTBL