Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PascalCase string to "Friendly Name" in TSQL

I have a table with a column whose values come from an Enumeration. I need to create a TSQL function to convert these values to "Friendly Names" upon retrieval.

Examples:

 'DateOfBirth' --> 'Date Of Birth'
 'PrincipalStreetAddress' --> 'Principal Street Address'

I need a straight TSQL UDF solution. I don't have the option of installing Extended Store Procedures or CLR code.

like image 843
Jose Basilio Avatar asked Aug 31 '25 10:08

Jose Basilio


1 Answers

/*
 Try this.  It's a first hack - still has problem of adding extra space
 at start if first char is in upper case.
*/
create function udf_FriendlyName(@PascalName varchar(max))
returns varchar(max)
as
begin

    declare @char char(1)
    set @char = 'A'

    -- Loop through the letters A - Z, replace them with a space and the letter
    while ascii(@char) <= ascii('Z')
    begin
        set @PascalName = replace(@PascalName, @char collate Latin1_General_CS_AS, ' ' + @char) 
        set @char = char(ascii(@char) + 1)
    end

    return LTRIM(@PascalName) --remove extra space at the beginning

end
like image 131
Rick Avatar answered Sep 03 '25 17:09

Rick