Friday, 13 September 2013

SQL For Applying Title Case to string

CREATE FUNCTION [Adhoc].[ApplyTitleCasing]
(
    @value nvarchar(1000)
)
RETURNS NVARCHAR(1000)
AS
BEGIN   
    Declare @individual varchar(1000) = null
    Declare @Seperator varchar(1) = ' '
    DECLARE @outputtable Table(VALUE NVARCHAR(1000) not null)
    DECLARE @CaseString NVARCHAR(1000)

    SET @CaseString = ''

    WHILE LEN(@value) > 0
    BEGIN
        IF PATINDEX('%' + @Seperator + '%',@value) > 0
        BEGIN
            SET @individual = SUBSTRING(@value, 0, PATINDEX('%' + @Seperator + '%',@value))
            INSERT INTO @outputtable values(LTRIM(RTRIM(@individual)))
            SET @value = SUBSTRING(@value, LEN(@individual + '|') + 1, LEN(@value))
        END
        ELSE
        BEGIN
            SET @individual = @value
            SET @value = NULL
            INSERT INTO @outputtable values(LTRIM(RTRIM(@individual)))
        END
    END

    SELECT @CaseString = @CaseString + ' ' + UPPER(SUBSTRING(VALUE,1,1)) + LOWER(SUBSTRING(VALUE,2,LEN(VALUE))) FROM @outputtable
    RETURN @CaseString
END

No comments:

Post a Comment