Link to home
Start Free TrialLog in
Avatar of Aleks
AleksFlag 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.
Avatar of _agx_
_agx_
Flag of United States of America image

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

Avatar of 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
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
...
ASKER CERTIFIED SOLUTION
Avatar of _agx_
_agx_
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Aleks

ASKER

Worked great! Thx.
Glad it helped!