Hi folks,
I’ve changed the t-sql code for Capitalize function, the previous capitalize function worked only if there is one space between words, but this version works even if there be more than one space between words.
with this version of Capitalize;
you can run the function like this:
select dbo.Capitalize(‘st charles‘)
and this is a sample result:
St Charles
I used this code to replace multiple spaces with one space.
and the result is the Capitalize function that works on words or sentences and even if there are multiple spaces in the input.
CREATE FUNCTION [dbo].[Capitalize]
(
@text varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
declare @outputtext varchar(max)
declare @spaceCount int
declare @counter int
declare @term varchar(max)
declare @index int
declare @spaceIndex int
set @outputtext=”
set @text=ltrim(rtrim(@text))
while charindex(‘ ‘,@text)>0
set @text=replace(@text,’ ‘,’ ‘)
set @spaceCount= len(@text)-len(replace(@text,’ ‘,”))
set @counter=0
set @index=1
while @counter<=@spaceCount
begin
if @index<>1
begin
set @index=@index+1
end
set @spaceIndex=charindex(‘ ‘,@text,@index)
if @spaceIndex=0
begin
set @spaceIndex=len(@text)+1
end
if @index<>1
begin
set @outputtext= @outputtext+’ ‘+ UPPER(substring(@text,@index,1))+LOWER(substring(@text,@index+1,(@spaceIndex-@index)-1))
end
else
begin
set @outputtext= @outputtext+ UPPER(substring(@text,@index,1))+LOWER(substring(@text,@index+1,(@spaceIndex-@index)-1))
end
set @counter=@counter+1
set @index=@spaceIndex
end
— Return the result of the function
RETURN @outputtext
END
you can run the function like this:
select dbo.Capitalize(‘st charles’)
and this is a sample result:
St Charles