Skip to main content
Inspiring
April 3, 2014
Answered

How to extract last name from a string

  • April 3, 2014
  • 1 reply
  • 578 views

I have SQL query that returns last name of a person and I need to extract the last part of any hyphenated or last names with a space in them

In cases where the person has one last name everything is OK

Like Smith. That OK. . I am looking for just Smith

The problem I have is when I have hyphenated last names like Scott-Thomas

In that case I want to extract the last last name or Thomas.

Or if I have a last name like Rodham Clinton.
In that case I only want to extract the last last name Clinton.

How do I do this?

    This topic has been closed for replies.
    Correct answer Carl Von Stetten

    Creative use of the ListLast() function.  Something like:

    <cfset variables.LastLastName = ListLast(myQuery.LastName, " -")>

    Notice that the optional 2nd parameter, which is a non-default delimiter, has a space and a hyphen between the quotes.  This will cause ListLast() to break a string containing either a space or a hyphen into multiple parts, and return only the last part.

    -Carl V.

    1 reply

    Carl Von Stetten
    Carl Von StettenCorrect answer
    Legend
    April 3, 2014

    Creative use of the ListLast() function.  Something like:

    <cfset variables.LastLastName = ListLast(myQuery.LastName, " -")>

    Notice that the optional 2nd parameter, which is a non-default delimiter, has a space and a hyphen between the quotes.  This will cause ListLast() to break a string containing either a space or a hyphen into multiple parts, and return only the last part.

    -Carl V.

    BKBK
    Community Expert
    Community Expert
    April 5, 2014

    <cfset variables.LastLastName = ListLast(myQuery.LastName, " -")>

    That is the best solution, of course. However, the eye can easily miss the space.

    The following slight change gives a bit of added value, for maintenance purposes:

    <cfset variables.LastLastName = ListLast(myQuery.LastName, "#chr(32)#-")>