sql-serveruppercaselowercase

Change the case on Mc surnames to proper case


I run a function to update some columns on a few tables to change UPPERCASE to ProperCase. I didn't take into account the 'Mc' or 'Mac' surnames. So now all my McSurnames have changed to Mcsurnames.

Does anyone have any scripts that would amend to McSurname?

Any help appreciated.

Thanks.


Solution

  • This can be a slippery slope. You will find many exceptions. That said, here is a scaled down version of my proper function.

    Example

    Select [dbo].[svf-Str-Proper]('john old macdonald ii phd,dds llc')
    

    Reurns

    (No column name)
    John Old MacDonald II PhD,DDS LLC
    

    The Function if Desired

    CREATE FUNCTION [dbo].[svf-Str-Proper] (@S varchar(max))
    Returns varchar(max)
    As
    Begin
        Set @S = ' '+replace(replace(Lower(@S),'   ',' '),'  ',' ')+' '
        ;with cte1 as (Select * From (Values(' '),('-'),('/'),('\'),('['),('{'),('('),('.'),(','),('&'),(' Mc'),(' Mac'),(' O''') ) A(P))
             ,cte2 as (Select * From (Values('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M')
                                           ,('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z')
                                           ,('LLC'),('PhD'),('MD'),('DDS')
                                           ,('II '),('III '),('IV ')
                                           ,('ID '),('PW ')
                                     ) A(S))
             ,cte3 as (Select F = Lower(A.P+B.S),T = A.P+B.S From cte1 A Cross Join cte2 B 
                       Union All 
                       Select F = Lower(B.S+A.P),T = B.S+A.P From cte1 A Cross Join cte2 B where A.P in ('&') 
                      ) 
        Select @S = replace(@S,F,T) From cte3 
        Return rtrim(ltrim(@S))
    End