kaustubh shukla
kaustubh shukla

Reputation: 37

Replacing spaces in comma separated string in SQL

Friends, I need some help..
I have a comma separated string in SQL in which I want to replace spaces between the commas.

I am using the following statement, but it's not working as expected

REPLACE(replace(@code,' ,',','),', ',',')

space before the comma is getting replaced with comma, but not the space after the comma.

Upvotes: 2

Views: 4501

Answers (2)

Joe G Joseph
Joe G Joseph

Reputation: 24116

try this:

declare @code varchar(50)=', this ,is a ,    test, '
while(PATINDEX ('% ,%',@code)>0 or PATINDEX ('%, %',@code)>0 )
select @code=REPLACE(replace(@code,' ,',','),', ',',')
select @code

Upvotes: 0

Dan Barzilay
Dan Barzilay

Reputation: 4993

Try doing this:

REPLACE(REPLACE(@code,' ,',','),', ',',')

I'm suggesting this because the replace statement is case-sensitive

Upvotes: 3

Related Questions