Proper UDF - Capitalize String as Proper Names

Tagged:

The ufn_Proper() UDF for SQL Server is similar to the VFP Proper() function. It additionally allows to specify a set of delimiters.

This is sample code. Add error handling and adjust to your requirements as necessary.

IF EXISTS (SELECT * FROM sysobjects WHERE name = N'ufn_Proper')
	DROP FUNCTION ufn_Proper
GO
 
-- Function ufn_Proper
CREATE FUNCTION ufn_Proper
	(
		@STR VARCHAR(8000),  
		@Delimiters VARCHAR(12) = ' ' 
	) 
RETURNS VARCHAR(8000)
-- @Str - source string to be converted to Proper format
-- @Delimiters - list of delimiters. Any letter after delimiter will be Upper cased. A space is default delimiter.
AS
BEGIN
	DECLARE @pos INT, @CharIsDelimiter CHAR(1)
 
	SET @CharIsDelimiter = 'Y'			-- 'Y' indicates that current character is a delimiter
	SET @STR 	= LOWER(@STR)			-- Convert whole string to lower case 
	SET @pos 	= 1						
 
	WHILE @pos <= LEN(@STR)
	BEGIN
		IF CHARINDEX(SUBSTRING(@STR, @pos, 1), @Delimiters) > 0
			-- The current character is a delimiter
			SET @CharIsDelimiter = 'Y'
		ELSE IF @CharIsDelimiter = 'Y'
		BEGIN 
			-- The current character is not a delimiter but previous character is
			--   Upper case the current character
			SET @STR = STUFF(@STR, @pos, 1, UPPER(SUBSTRING(@STR, @pos, 1)))
			SET @CharIsDelimiter = 'N' 
		END
		SET @pos = @pos + 1
	END	
	RETURN @STR
END
GO
 
-- Sample of using ufn_Proper UDF
 
SELECT dbo.ufn_Proper('The quick brown fox jumps over the lazy dog', DEFAULT)