I am trying to write a stored procedure in sql server 2008,I need to remove unwanted spaces in the entries of my table.I categorized the entries in my table to 3 types.My store procedure should remove the spaces around single letter,like,
A G M wordstoAGM wordswords A G M wordstowords AGM wordsA G wordstoAG words
I tried following stored procedure.
CREATE proc At1 @name nvarchar(100)
as
declare @start int
declare @temp1 nvarchar(100)
declare @temp nvarchar(100)
declare @NthPosition int
declare @N int
set @N=LEN(@name)
set @start=1
set @temp1=''
set @temp=''
set @NthPosition=charindex(' ',@name,@start)
if(@NthPosition<>0)
begin
while (@NthPosition<>0 and @N<>0)
begin
set @temp1=SUBSTRING(@name,@start,@NthPosition-1)
if(@temp<>'')
begin
if(len(@temp1)=1)
begin
set @temp=(@temp+@temp1)
end
else
begin
set @temp=(@temp+' '+@temp1)
end
end
else
begin
set @temp=@temp1
end
set @start=@NthPosition+1
set @N=@N-@NthPosition
set @NthPosition=0
set @NthPosition=CHARINDEX(' ',@name,@start)
end
end
else
begin
select @name
end
select @temp
GO
and i used ,
exec At1 'apple A G M mango'
My expected result: apple AGM mango
But my actual result:apple
I am unable to figure out where the error is..Any suggestions in this regard is more helpful.
I tried to use computed column that would clear the space and i was able to find solution only for pattern #3.I am unable to frame a computed column definition suitable for all the 3 patterns….. Please share your thoughts that will be helpful to me
I think this covers all the cases:
And the examples:
Produces:
(As a simplifying assumption, I assumed I was okay to remove any leading spaces from the original string. I also assume there are no double spaces in the string. If neither of those assumptions is accurate, a bit more work is required)