Technical Article

Function to return proper case

,

Pass in the string you wish to check for proper case. If you separate the string by spaces it will check each word and capitalize the first letter. You can pass in as many words separated by a space as you wish. I hope you enjoy this function.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select dbo.[ufnProperCase]('bob smith')
--select dbo.[ufnProperCase]('bob davis smith')
ALTER function [dbo].[ufnProperCase] (@expression nvarchar(4000)) returns nvarchar(4000)
as
begin
    declare @i smallint, @properexpression nvarchar(4000), @lenexpression smallint, @flag bit, @symbol nchar(1)
    
    select @flag = 1, @i = 1, @properexpression = '', @lenexpression = datalength(@expression)/(case SQL_VARIANT_PROPERTY(@expression,'BaseType') when 'nvarchar' then 2 else 1 end) 
    
    while @i <= @lenexpression
        begin
            select @symbol = lower(substring(@expression, @i, 1) )
            if @symbol in (nchar(32), nchar(9), nchar(10), nchar(11), nchar(12), nchar(13), nchar(160)) and ascii(@symbol) <> 0
                select @flag = 1
            else
                if @flag = 1
                    select @symbol = upper(@symbol), @flag = 0 
                    select @properexpression = @properexpression + @symbol, @i = @i + 1 
        end

    return @properexpression
end

Rate

3 (12)

You rated this post out of 5. Change rating

Share

Share

Rate

3 (12)

You rated this post out of 5. Change rating