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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.