Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 How to Remove Extra Spaces in a String

Author  Topic 

AnupamaB96
Starting Member

1 Post

Posted - 2013-07-24 : 10:16:25
Hi,

I am using sql server 2008.
I have a "Description"column in my database which is a string which has more than 2 spaces in between the words and the spaces are different for each record

Description1='AAAA BBBB CCCC'
Description2='AAAA BBBB CCCC'
Description1='AAAA BBBB CCCC'


I only want a single space between the words.

I tried using REPLACE but i have to use it multiple times to get the single space like hardcoding.Is there a way to write a loop such that it checks and as result we get only one space between the words?

Thanks in advance

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-07-24 : 10:24:03
SQL Server has very few string manipulation functions, so you are pretty much stuck with what you described. You can nest the REPLACE statements, so you can find the largest consecutive number of spaces anywhere and nest replace that many times.

Another option, if you really want to, is to split the strings using space as the delimiter and then reassemble the split strings with a single space as the delimiter. Not too hard, but I would prefer the nested replace statement unless there was some compelling reason to use another approach.
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-07-24 : 10:24:58
see here:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=162393


Too old to Rock'n'Roll too young to die.
Go to Top of Page
   

- Advertisement -