ALTER FUNCTION Proper_Case(@string VARCHAR(255)) RETURNS VARCHAR(255)
AS
BEGIN
  DECLARE @int_posn INT		--index
  DECLARE @len_str INT			--input length
  DECLARE @cur_chr NCHAR(1)		--current char
  DECLARE @first_chr INT		--first letter flag (1/0)
  DECLARE @output_str VARCHAR(255)	--output string
  --List of special characters that we need to remove
  --including white space, carriage returns, linefeeds, 
  --tabs or spaces
  DECLARE @w_space VARCHAR(10)	

  --set the variables with their corresponding values
  --assign the list of special characters 
  --to the corresponding character
  SET @w_space = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160)
        		+  CHAR(32)  + ']'
  --assign a value to the first integer position
  SET @int_posn = 1
  --establish the length of the string to be parsed
  SET @len_str = LEN(@string)
  --set the flag to indicate that we are at the first char.
  SET @first_chr = 1	
  --assign the output_str to an empty string				
  SET @output_str = ''	
 
  --loop through all characters in the string
  WHILE @int_posn <= @len_str --while we are not at the end…	
  BEGIN
    --Fetch the first letter.
    SET @cur_chr = SUBSTRING(@string, @int_posn, 1)
	--If this is the first letter of a word…
    IF @first_chr = 1				
		BEGIN
			  --Covert the letter to upper case and add it to out output
			  SET @output_str = @output_str + UPPER(@cur_chr)
			  --set the first character flag to 0 
			  SET @first_chr = 0		
		END
    ELSE	--it’s not the first character
		BEGIN
		  --Covert the letter to lower case and add it to out output
		  SET @output_str = @output_str + LOWER(@cur_chr)
		END
    --If the current character is a special character
    --then we need to set the flag to 0 to indicate the next  
    --character will be the first character in a word.
    IF @cur_chr LIKE @w_space	
    	SET @first_chr = 1
    -- increment the counter
    SET @int_posn = @int_posn + 1	
  END --End of the loop
--Now we can return the output we have built up in the loop
RETURN @output_str				
END; --End of our function

go

SELECT dbo.proper_case('tEsT TheSe WoRdS') as proper_case