Avatar of Aleks
Aleks
Flag for United States of America asked on

SQL to separate last name from first name

I have a table called 'cases', one of the fields is a field called 'Name', it includes the full name of the person.
I need to separate the name and move the first name to the "FirstNm" field and the last name into the "LastNm" field

How can I run a query so that it will remove any blank characters (spaces) before the first word, then the first word is the "FirstNm" and everything after the first word (space), will be the last name, the last name may include spaces, such as "De La Praga"

So that this name:  Ana De La Praga  (Name), would be separated as:
FirstNm:  Ana
LastNm:  De La Praga

Table Name: cases

Helps is greatly appreciated.
Web DevelopmentSQL

Avatar of undefined
Last Comment
_agx_

8/22/2022 - Mon
_agx_

If you search the archives, you'll find a lot of topics on it, such as this one.  Keep in mind separating based on spaces doesn't properly handle edge cases like "FirstName Middle LastName". Not sure of your dbms, but for SQL Server, try


-- sample table
DECLARE @YourTable TABLE
(
id integer identity
, Name nvarchar(200)
, FirstNm nvarchar(100)
, LastNm nvarchar(100)
)
-- sample data
INSERT INTO @YourTable (Name)
VALUES 
(' Ana De La Praga')
, ('Joe Miller')
, ('Ronald D McDonald')

-- update
;WITH tbl AS
(
	SELECT LTRIM(RTRIM(Name)) AS Name
			, FirstNm
			, LastNm
			, CHARINDEX(' ', LTRIM(RTRIM(Name))) AS SpacePos
	FROM   @YourTable
)
UPDATE tbl
SET    FirstNm = CASE WHEN SpacePos > 1 THEN SUBSTRING(Name, 1, SpacePos) ELSE Name END
		, LastNm = CASE WHEN SpacePos > 1 THEN SUBSTRING(Name, SpacePos+1, LEN(Name)-SpacePos) ELSE NULL END

-- display results
;SELECT * FROM @YourTable

Open in new window

Aleks

ASKER
Can we please us the code with the table and field names described above?   I am not interested in the Middle Name.
The first word as explained is the FirstNm, then a space, anything after that space is LastNm
_agx_

It does use the 3 field names you mentioned:   Name, FirstNm and LastNm.  If you are using SQL Server, please try the previous example.  

,,,,
UPDATE tbl
SET    FirstNm = CASE WHEN SpacePos > 1 THEN SUBSTRING(Name, 1, SpacePos) ELSE Name END
            , LastNm = CASE WHEN SpacePos > 1 THEN SUBSTRING(Name, SpacePos+1, LEN(Name)-SpacePos) ELSE NULL END
...
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
_agx_

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Aleks

ASKER
Worked great! Thx.
_agx_

Glad it helped!