将 PascalCase 字符串转换为“友好名称"在 TSQL 中

2021-09-15 00:00:00 user-defined-functions tsql sql-server

我有一个表,其中一列的值来自枚举.我需要创建一个 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.

示例:

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

我需要一个直接的 TSQL UDF 解决方案.我没有安装扩展存储过程或 CLR 代码的选项.

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

推荐答案

/*
 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

相关文章