Here's a UDF that also removes extraneous spaces.
ALTER FUNCTION [dbo].[udfCamelCase]
(
-- Add the parameters for the function here
@VStringvarchar(1000)
)
RETURNS varchar(1000)
AS
BEGIN
-- Table used to get the words in the string
DECLARE @PartTable table (StringPart varchar(100));
-- Variable to hold each part of the return string
DECLARE @HWordvarchar(100);
-- These variables are used to "clean" the string, i.e., make sure only
-- one space exists between the parts of the string
DECLARE@CNvarchar(200);
DECLARE@Xvarchar(100);
DECLARE@Iint;
DECLARE @HString varchar(1000);
DECLARE@RetVarvarchar(1000);
IF @VString = '' OR @VString IS NULL
RETURN '';
SET @HString = RTRIM(LTRIM(@VString));
SET @I = CHARINDEX(' ',@HString);
-- If there are no spaces just make the first character upper case and return it
IF @I = 0
BEGIN
SET @RetVar = UPPER(SUBSTRING(@HString,1,1));
SET @RetVar = @RetVar + LOWER(SUBSTRING(@HString,2,LEN(@HString) - 1));
RETURN @RetVar;
END
WHILE (@I != 0)
BEGIN
SET @RetVar = UPPER(SUBSTRING(@HString,1,1));
SET @RetVar = @RetVar + LOWER(SUBSTRING(@HString,2,@I - 1));
INSERT@PartTable
SELECT@RetVar;
SET @HString = LTRIM(RTRIM(SUBSTRING(@HString,@I+1,LEN(@HString) - @I)));
SET @I = CHARINDEX(' ',@HString);
END
IF LEN(@HString) > 0
BEGIN
SET @RetVar = UPPER(SUBSTRING(@HString,1,1));
SET @RetVar = @RetVar + LOWER(SUBSTRING(@HString,2,LEN(@HString) - 1));
INSERT@PartTable
SELECT@RetVar;
END
SET @HString = '';
WHILE ((SELECT COUNT(*) FROM @PartTable) > 0)
BEGIN
SELECTTOP (1) @HWord = LTRIM(RTRIM(StringPart))
FROM@PartTable;
DELETETOP (1)
FROM@PartTable;
IF @HString = ''
SET @HString = @HWord;
ELSE
SET @HString = @HString + ' ' + @HWord;
END
--RETURN @DBVar;
RETURN @HString;
END