I am trying to split a full name with Prefix
, First Name
, Middle Name
and Last Name
using SQL Server.
I have tried the following but it is not working properly as desired output is not correct.
Code
SELECT TOP 10
ID,
FullName,
SUBSTRING(FullName, CHARINDEX(' ', FullName) + 1, LEN(FullName)) AS Full_Name,
SUBSTRING(FullName, 1, CHARINDEX(' ', FullName)) AS Prefix,
SUBSTRING(FullName, CHARINDEX(' ', FullName), LEN(FullName) - CHARINDEX(' ', REVERSE(FullName)) - CHARINDEX(' ', FullName) + 1) FirstName,
RIGHT(FullName, CHARINDEX(' ', REVERSE(FullName)) - 1) AS Last_Name,
LEN(SUBSTRING(FullName, CHARINDEX(' ', FullName), LEN(FullName) - CHARINDEX(' ', REVERSE([FullName)) - CHARINDEX(' ', FullName) + 1)) AS FirstNameChar
FROM
Names WITH (NOLOCK)
WHERE
(FullName LIKE 'Mr %' OR
FullName LIKE 'Mrs %' OR
FullName LIKE 'Miss %' OR
FullName LIKE 'Ms %' OR
FullName LIKE 'Dr %')
Current output:
ID | FullName | Prefix | FirstName | Last_Name | FirstNameChar |
---|---|---|---|---|---|
123456 | Mr s t Fenech | Mr | s t | Fenech | 4 |
Required output:
ID | FullName | Prefix | FirstName | Middle_Name | Last_Name | FirstNameChar |
---|---|---|---|---|---|---|
123456 | Mr s t Fenech | Mr | s | t | Fenech | 1 |
I want to remove the spaces from before the first name and Last Name as can be see the FirstNameChar is 4 when actually should be 1 and be able to split also the middle name.
Anyone can help with this?
Reference to question on stackoverflow: SQL- Get the substring after first space and second space in separate columns
SQL: parse the first, middle and last name from a fullname field