这是一个简单的基于集合的方法,通过应用三个替换将多个空格折叠成一个空格。
DECLARE @myTable TABLE (myTextColumn VARCHAR(50))
INSERT INTO @myTable VALUES ('0Space')
INSERT INTO @myTable VALUES (' 1 Spaces 1 Spaces. ')
INSERT INTO @myTable VALUES (' 2 Spaces 2 Spaces. ')
INSERT INTO @myTable VALUES (' 3 Spaces 3 Spaces. ')
INSERT INTO @myTable VALUES (' 4 Spaces 4 Spaces. ')
INSERT INTO @myTable VALUES (' 5 Spaces 5 Spaces. ')
INSERT INTO @myTable VALUES (' 6 Spaces 6 Spaces. ')
select replace(
replace(
replace(
LTrim(RTrim(myTextColumn)), ---Trim the field
' ',' |'), ---Mark double spaces
'| ',''), ---Delete double spaces offset by 1
'|','') ---Tidy up
AS SingleSpaceTextColumn
from @myTable
您的更新语句现在可以基于:
update @myTable
set myTextColumn = replace(
replace(
replace(
LTrim(RTrim(myTextColumn)),
' ',' |'),
'| ',''),
'|','')
使用适当的 Where 子句将更新限制为仅包含您需要更新或可能包含双空格的行。
例子:
where 1<=Patindex('% %', myTextColumn)
我找到了关于这种方法的外部文章:REPLACE Multiple Spaces with One