/*Since I didn't write articles in eng for a while, I decide to make the explanation in eng. :P*/
/*The code is from SQL Server 2005 Bible and the footnote is my individual understanding on it.*/
--An interesting code to be the starting point for this section
--This function can realize the following example.
--Input ('haHa lolA') and it returns Haha Lola in the table.
--Below is the part how SQL creates a function;
Create FUNCTION pTitleCase (
@StrIn varchar(1024)) --It's better if everything in eng. Or the string may make the function wrong.
RETURNS varchar(1024)
AS
BEGIN
DECLARE
@StrOut varchar(1024),
@CurrentPosition INT,
@NextSpace INT,
@CurrentWord varchar (1024),
@StrLen INT,
@LastWord BIT
Set @NextSpace = 1
Set @CurrentPosition = 1
Set @StrOut = ''
Set @StrLen = Len(@StrIn)
Set @LastWord = 0
While @LastWord = 0
BEGIN
Set @NextSpace = charindex(' ', @StrIn, @CurrentPosition+1) --Find whether a SPACE in the input string for each one step.
IF @NextSpace = 0 --No more space found!
BEGIN
Set @NextSpace = @StrLen
Set @LastWord = 1 --Terminal of the loop
END
Set @CurrentWord = UPPER(substring(@StrIn, @CurrentPosition,1)) --If a SPACE found in the charindex line, it changes the alphebet following the SPACE uppercase.
Set @CurrentWord = @CurrentWord + Lower(Substring(@StrIn,@CurrentPosition+1,@NextSpace-@CurrentPosition)) --After it puts all the alphebets following the UPPERCASE alphebet to lowercase...
Set @StrOut = @StrOut +@CurrentWord --Appending...
Set @CurrentPosition = @NextSpace + 1
--2015-Jan-18 00:51 Not Sure why it is here??????????? Feel Like a bug.
--2015-Jan-19 09:45 This is not a bug, after reviewing the code, this one should read with the charindex line. The current position would jump to next space position plus one step.
END
Return @StrOut
END
And then when you
Select dbo.pTitleCase ('one TWO tHree') as [TitleCase]
It shows One Two Three under Column TitleCase.