Blog - Single Post

SQL Server function to convert a string to Pascal Case

IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[dbo].[udf_PascalCase]')
                    AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ) )
    DROP FUNCTION [dbo].[udf_PascalCase];
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE FUNCTION [dbo].[udf_PascalCase] ( @Text NVARCHAR(MAX) )
RETURNS NVARCHAR(MAX)
AS
    BEGIN
        SET @Text = LOWER(@Text);
        DECLARE @New NVARCHAR(MAX) = ( CASE WHEN @Text IS NULL THEN NULL
                                            ELSE ''
                                       END );
        DECLARE @Len INT = LEN(REPLACE(@Text, ' ', '_'));
        DECLARE @Index INT = 1;
        WHILE ( @Index <= @Len )
            IF ( SUBSTRING(@Text, @Index, 1) LIKE '[^a-z]'
                 AND @Index + 1 <= @Len
               )
                SELECT  @New = @New + UPPER(SUBSTRING(@Text, @Index, 2)) ,
                        @Index = @Index + 2;
            ELSE
                SELECT  @New = @New + SUBSTRING(@Text, @Index, 1) ,
                        @Index = @Index + 1;

        RETURN ( UPPER(LEFT(@New, 1)) + RIGHT(@New, ABS(@Len - 1)) );
    END;
GO