Change John Smith to Smith, John

  • I have a list of names like this:

    John Smith

    Bob Johnson

    Earl Time

    I need convert these to this:

    Smith, John

    Johnson, Bob

    Time, Earl

    How can I do this through T-SQL?

    _______________________________
    [font="Tahoma"]Jody Claggett
    SQL Server Reporting Analyst
    [/font][/size]

  • Where does the list reside? Do you ever have a middle name/initial or Suffix? Ideally the database design would change to have separate columns for first, middle, and last names then you concatenate however you want.

    Declare @table table(name varchar(50))

    Insert into @table

    Select

    'John Smith' Union Select

    'Bob Johnson'Union Select

    'Earl Time'

    Select

    charindex(' ', name),

    Substring(name, 0, charindex(' ', name)) as first_name,

    Substring(name, charindex(' ', name) + 1, len(name)) as last_name ,

    Substring(name, charindex(' ', name) + 1, len(name)) + ', ' + Substring(name, 0, charindex(' ', name)) as full_name ,

    name

    From

    @table

    How's that?

  • This one deserves some thinking through/ahead

    What's the rationale behind this swap? What if you have to swap back in the future?

    Will it be easier to split them into a FirstName, MiddleName, LastName columns now?

    You need to deal with the cases with middle names anyway

    SQLServerNewbieMCITP: Database Administrator SQL Server 2005
  • This kind of manipulation is tricky when you find people with more than one word in their name like " Kate van der Mullen"


    * Noel

  • Thanks everyone. Jack's solution looks like it is going to work for me.

    I don't have the ideal situation in that the field contains the full name of the employee and the first and last names are not in seperate columns. That being said, however this is only a one time data cleansing and update. Going forward, the names will be stored in the new format.

    Before this is done, I will backup the existing data and store this with both versions. So if I need to revert back, I can.

    _______________________________
    [font="Tahoma"]Jody Claggett
    SQL Server Reporting Analyst
    [/font][/size]

  • I'd be sure to check data quality with this. It appears to work, but Kendall Van Dyke might not work well, as perhaps John A. Smith.

    You want to look for those exceptions, and then perhaps do some additional handling on them.

  • Think about doing a query to list names contain more than two strings (more than one space '% % %'). You will want to change those individually.

    Billy Bob Thornton

    John Q. Public

    Reggie Rucker Jr.

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply