Use Atlantic;
GO
IF EXISTS (SELECT *
			FROM sys.objects
			WHERE object_id = OBJECT_ID (N'dbo.udf_Proper_Case')
				AND type IN(N'FN', N'TF', N'IF'))
DROP FUNCTION dbo.udf_Proper_Case
GO
CREATE FUNCTION udf_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
  DECLARE @w_space VARCHAR(10)		--characters considered as white space
									-- carriage return, linefeed,
									-- tab or space

  SET @w_space = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160) +  CHAR(32)  + ']'	--define the set of characters respected as white space e.g. carriage return
  SET @int_posn = 1				--assign a value to the first integer position
  SET @len_str = LEN(@string)	--establish the length of the string to be parsed
  SET @first_chr = 1			--initialise the first_chr 				
  SET @output_str = ''			--assign the output_str to an empty string

  WHILE @int_posn <= @len_str	--loop through all characters in the string
  BEGIN
    SET @cur_chr = SUBSTRING(@string, @int_posn, 1)
    IF @first_chr = 1				--test if the variable has been assigned to one (first character in the delimited string)
		BEGIN
			SET @output_str = @output_str + UPPER(@cur_chr)		--any character with a flag (@first_chr) of 1 will be returned in Upper Case
			SET @first_chr = 0		--reassign the variable to zero after the first character has been converted
		END
    ELSE
		BEGIN
			SET @output_str = @output_str + LOWER(@cur_chr)		--executed if the flag is zero (not the first character in the current delimited string 'word')
		END
		IF @cur_chr LIKE @w_space SET @first_chr = 1		--test if the current character is a declared white space character
--			SET @first_chr = 1				--if true, reassign the variable to one (the first character in the new word)
		SET @int_posn = @int_posn + 1	-- increment the counter
	END
  RETURN @output_str				--return the rebuilt string in Proper Case
END;
GO