Help parsing a field

Hi..
I need help parsing a NAME field. I only want to parse - extract the First and Last Names if the NAME field just contains 2 'words'  like this

JOHN SMITH
OR
JANE DOE

I don't want to parse if it contains a middle or additional info
like this
ROBERT JOHN BROWN
ROB A. GREEN
ROB AND MARY SMITH
THE ABC CORPORATION
LVL 1
JElsterAsked:
Who is Participating?
 
Ephraim WangoyaCommented:

try
declare @fullname varchar(30)

set @fullname = 'john doe'

select case 
          when LEN(@fullname) - LEN(REPLACE(@fullname, ' ', '')) = 1 then
            LEFT(@fullname, CHARINDEX(' ', @fullname, 1))
          else 
            ' '
        end [First Name],
        case 
          when LEN(@fullname) - LEN(REPLACE(@fullname, ' ', '')) = 1 then
            RIGHT(@fullname, LEN(@fullname) - CHARINDEX(' ', @fullname, 1))
          else 
            ' '
        end [Last Name]

Open in new window

0
 
Lee SavidgeCommented:
declare @NAME nvarchar(100)
select @NAME = 'john smith'

if len(rtrim(ltrim((@NAME))) - replace(@NAME, ' ', '') > 1
  print 'More than one space'
else
  print 'Only one space'

You can remove the ltrim and rtrim if you aren't worried about leading and trailing spaces. However, what if the person has a surname like 'van den surname' which contains spaces naturally?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.