SQL: How can I Parse firstname, lastname and title from fullname? - sql-server

I have a column named Employee name in table 1
Example: Mr.FirstName LastName
and so on with various titles but there are employee names without the title in the same column.I am about to split the single column and do an insert in the new table (table 2) with three different columns like FirstName, LastName and Title.So while doing an insert into the new table I am not able to split the employee column name like I mentioned.Any help will be really appreciated I started with LINQ so I am not aware of much SQL functions.
Update : Sample data

Here's one example.
DECLARE #name varchar(100) = 'Mr.FirstName LastName'
SELECT
LEFT(#name, CHARINDEX('.', #name)) AS Title,
SUBSTRING(#name, CHARINDEX('.', #name)+1, CHARINDEX(' ', #name)-CHARINDEX('.', #name)) AS FirstName,
SUBSTRING(#name, CHARINDEX(' ', #name)+1, 1000) AS LastName
It takes...
the left part till the . as Title.
everything after the . until the first space as FirstName
everything after the first space as LastName
Note: There's no check for errors, if the name does not fit into this pattern.

For the simplest case you specified in the question the following query should work
SELECT *,
SUBSTRING(Employee_name, 0, CHARINDEX('.', Employee_name)) AS Title,
SUBSTRING(Employee_name,
CHARINDEX('.', Employee_name)+1,
CHARINDEX(' ', Employee_name)) AS FirstName,
SUBSTRING(Employee_name,
CHARINDEX(' ', Employee_name)+1,
LEN(Employee_name)) AS LastName
FROM Employee;

Related

Divide personal names in separate columns

I have one table which is called #MyNames.This table in one column contain full name of persons (Name space Surname). In this column we can distinct name from surname with space with them.From left side we have name and after space we have surname.Below you can see table:
So my intention is to divided this column with name MyFullName into two separate columns called ,,FirstName" and ,,LastName''. In order to do this i try with this code:
SELECT LEFT(MyFullName,charindex(' ', MyFullName) - 1) AS FirstName, RIGHT(MyFullName,charindex(' ', MyFullName)-1 ) AS LastName
from #MyNames
Output from this code is not good and I have results like table below :
So can anybody help me how to fix this code and get result correctly and to have fist name in one column and second name in other column?
Obviously the surname clause isn't working correctly.
Instead of using RIGHT(MyFullName,charindex(' ', MyFullName)-1 ) consider SUBSTRING(MyFullName,charindex(' ', MyFullName) + 1, 100) (or whatever field length is).
A better approach (though less easy to read imo) is to replace the first name component with blank '' characters.
STUFF(MyFullName,1,charindex(' ', MyFullName),'')
These should both work
SELECT LEFT(MyFullName,charindex(' ', MyFullName)-1) AS FirstName,
SUBSTRING(MyFullName,charindex(' ', MyFullName)+1, 100) AS LastName
from #MyNames
SELECT LEFT(MyFullName,charindex(' ', MyFullName)-1) AS FirstName,
STUFF(MyFullName,1,charindex(' ', MyFullName),'') AS LastName
from #MyNames
A small correction in your query should fix the problem.
SELECT LEFT(MyFullName,charindex(' ', MyFullName) - 1) AS FirstName
, RIGHT(MyFullName,len(MyFullName) - charindex(' ', MyFullName)) AS LastName
from #MyNames

Parse Thai Name into First Last

I need to parse a list of FullNames into First and Last Name. If a middle name is included, it should be included in the fist name field.
John Smith would be:
FirstName = John
LastName = Smith
John J. Smith would be:
FirstName = John J.
LastName = Smith
The issue is the names might be either Thai or English character set. I need to properly parse either set. I have tried just about everything...
DECLARE #FullName NVARCHAR(MAX) = N'กล้วยไม้ สวามิวัศดุ์'
--DECLARE #FullName NVARCHAR(MAX) = N'Mark C. Wilson'
SELECT
LEN(#FullName) AS StringLength,
LEN(#FullName) - LEN(REPLACE(#FullName,N' ', N'')),
LEN(REPLACE(#FullName,N' ', N'')),
#FullName AS FullName,
REVERSE(#FullName) AS ReverseName, -- This is obviously no Reverse of the string
CHARINDEX(N' ', REVERSE(#FullName)) AS LastSpaceLocation,
CHARINDEX(N' ', #FullName) AS FirstSpaceLocation,
LEN(#FullName) AS LenString,
STUFF(#FullName, 1, CHARINDEX(N' ', #FullName), N'') as FirstName,
RIGHT(#FullName, LEN(#FullName) - CHARINDEX(N' ', #FullName) + 1) as LastName,
LEFT(#FullName, LEN(#FullName) - CHARINDEX(N' ', REVERSE(#FullName))) AS FirstName,
STUFF(RIGHT(#FullName, CHARINDEX(N' ', REVERSE(#FullName))),1,1,N'') AS LastName,
LEN(#FullName),
REVERSE(#FullName),
REVERSE(' '),
LEN(#FullName) - CHARINDEX(reverse(' '), REVERSE(#FullName)) - LEN(' ') + 1
The REVERSE simply does not work when the Thai character set is used.
I can't read Thai (I'm not that bright), but perhaps this may help.
Here we are using a CROSS APPLY to "fix" the string, and then it is a small matter of PasrName() and Concat()
I should add, parsing names is a slippery slope. One needs to consider
Multi Word Last Names ie De la Cruz
Suffix ie. Richard R Cappelletti MD
Example
Declare #YourTable table (FullName nvarchar(100))
Insert Into #YourTable values
('John Smith')
,('John J. Smith')
,(N'กล้วยไม้ สวามิวัศดุ์')
Select A.*
,LastName = replace(parsename(S,1),'|','.')
,FirstName = replace(concat(parsename(S,4),' '+parsename(S,3),' '+parsename(S,2)),'|','.')
From #YourTable A
Cross Apply ( values (replace(replace(FullName,'.','|'),' ','.'))) B(S)
Returns
FullName LastName FirstName
John Smith Smith John
John J. Smith Smith John J.
กล้วยไม้ สวามิวัศดุ์ สวามิวัศดุ์ กล้วยไม้
EDIT 2008 Version
Select A.*
,LastName = replace(parsename(S,1),'|','.')
,FirstName = replace( IsNull(parsename(S,4),'') + IsNull(' '+parsename(S,3),'') + IsNull(' '+parsename(S,2),''),'|','.')
From #YourTable A
Cross Apply ( values (replace(replace(FullName,'.','|'),' ','.'))) B(S)
I'm Thai and one thing I know is that Thai people don't do middle name.

How to switch data in a column and update the column with result information in SQL Server

I have a table USERS and it has a column FULLNAME that contains full users names in the format FirstName LastName and I need to switch the data, and update it in the same column, using this format LastName, FirstName.
Ex. James Brown needs to be switched to Brown, James and updated in the same column (FULLNAME)
Is there any way to do it?
Thanks.
The best solution would be to split the elements into two columns (LastName, FirstName). However, if you want to try and squeeze it into 1 column, and you're assuming that every name is split by a single space
DECLARE #Users TABLE ( Name VARCHAR(100) )
INSERT INTO #Users
( Name
)
SELECT 'James Brown'
UNION ALL
SELECT 'Mary Ann Watson'
SELECT RIGHT(Name, CHARINDEX(' ', REVERSE(Name)) - 1) + ', ' + LEFT(Name,
LEN(Name)
- CHARINDEX(' ',
REVERSE(Name)))
FROM #Users
This also assumes that if they have more than two names sperated by a space, then the last word is the last name, and everything else is first name. Works for "Mary Ann Watson", but not "George Tucker Jones", if "Tucker Jones" is a last name.
Assuming they only have 1 space in the name:
UPDATE USERS
SET FULLNAME = RIGHT(FULLNAME,len(FULLNAME) - CHARINDEX(' ',FULLNAME)) +', '+ LEFT(FULLNAME,charindex(' ',FULLNAME)-1)
WHERE LEN(FULLNAME) - LEN(REPLACE(FULLNAME, ' ', '')) = 1

Working on String concatenation with parsename function in sql server

I have a employee table and the sample data in it is like this. I am using sql server 2008.
CREATE TABLE employee (name nvarchar(255))
insert into employee (name) values ('Alex,AlexMartin'),
('John,John'),
('Mayr,Mayr'),
('Shel,Sheila'),
('corolla,corolla,corolla3'),
('Mary4,Mary,Mary'),
('Justin,Justin,Justin'),
('Sara,Sara,Sara,Sara'),
('clarence,clarence,clarence458,clarence,clarence'),
('fiesta,fiesta,fiesta,fiesta,fiesta'),
('scorpio1,scorpio,scorpio,scorpio4,scorpio')
I want to delete a value if all the values in the string are same example: John,John should be replaced by 'John'. If all the names in string are not equal like Shel,Sheila it should retain both the values.
For this I am using
update employee set name=(select PARSENAME(REPLACE(name, ',', '.'), 2)) where (select PARSENAME(REPLACE(name, ',', '.'), 2))
like (select PARSENAME(REPLACE(name, ',', '.'), 1)) but it is changing Mary4,Mary,Mary to Mary. I tried combinations for 5, 4, and 3 names but there is no use. In fact for five names this code is not at all working. Is there any efficient way to do this?
This will get the data in the format you're looking for:
CREATE TABLE #Employee (Name NVarChar(255));
INSERT INTO #Employee (Name) VALUES ('Alex,AlexMartin'),
('John,John'),
('Mayr,Mayr'),
('Shel,Sheila'),
('corolla,corolla,corolla3'),
('Mary4,Mary,Mary'),
('Justin,Justin,Justin'),
('Sara,Sara,Sara,Sara'),
('clarence,clarence,clarence458,clarence,clarence'),
('fiesta,fiesta,fiesta,fiesta,fiesta'),
('scorpio1,scorpio,scorpio,scorpio4,scorpio'),
('Another');
SELECT Name, CASE
WHEN CHARINDEX(Name, ',') = 0 THEN Name
WHEN
REPLACE(REPLACE(Name, LEFT(Name, CHARINDEX(',', Name) - 1), ''), ',', '') = ''
THEN LEFT(Name, CHARINDEX(',', Name) - 1)
ELSE Name
END Result
FROM #Employee;
DROP TABLE #Employee;
It works by getting the first name in the comma-separated list. By your requirements all of the items have to be identical in order to condense the list, so it doesn't matter which element in the list we use for comparison.
All occurrences of the first item are removed from the list. Then all of the commas are removed. If the resulting value is empty (i.e. '') then we know all of the items are identical. In that case the first element is used as the Result value. Otherwise, we return the original list unchanged.
EDIT: Some of your data mustn't have a , in it, so I've updated the answer to take care of that. It will just return the same input if a delimiter doesn't exist.

remove separator in sql server 2008

i have this query select(','+firstname +Lastname) from <tablename>
i have to remove , in result
So remove it:
SELECT firstname + Lastname
FROM tablename
Do you mean
select coalesce(Lastname + ', ' + firstname, firstname, lastname)
from <tablename>
Sounds like a simple string replace to me
SELECT REPLACE(',' + firstname + Lastname, ',', '')
FROM <tablename>
Although I don't really get why you're concatenating a comma to the beginning of your result if you don't need it anyway.

Resources