-2

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
MalcolmPH
  • 19
  • 5

2 Answers2

0

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
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
0

If we start by putting the prefix in a variable.

Then we need to filter the table so that it has at least two characters after that.

We update the table, so that the new value is the prefix, followed by the uppercase of the next letter, followed by the rest of the original value.

DECLARE @prefix nvarchar(100) = 'Mc'; -- or Mac

UPDATE table
SET lastname = @prefix + UPPER(SUBSTRING(lastname, LEN(@prefix) + 1, 1)) + SUBSTRING(lastname, LEN(@prefix) + 2, LEN(lastname)
WHERE lastname LIKE @prefix + '[a-z][a-z]%';

You can run this twice with the two different prefixes.

Charlieface
  • 52,284
  • 6
  • 19
  • 43