Hi,
What if the order of names is different?
Can you confirm 100% that First name comes always before Last name and these two always comes before the Middle name?!?
And what if the first name includes two words?!?
You should have redesign you database better so that the data will be inserted from the start to three explicit columns in this case. Any solution we will provide will never give you the guarantee that the result is as expected if you cannot control the input in this case!
Just for the sake of the discussion with a huge recommendation NOT TO USE IT IN PRODUCTION, but instead redesign your system
This cover your current sample data:
use tempdb
GO
CREATE TABLE tbl (id int identity(1,1) PRIMARY KEY, string varchar(100));
GO
INSERT INTO tbl VALUES
('FirstName LastName.'),
('FirstName , LastName'),
('FirstName , LastName M'),
('FirstName LastName MiddleName');
GO
;With MyCTE AS (
select id, string, EditedString =
REPLACE(replace(replace(replace(REPLACE(REPLACE(string,'.',''), ',',' '),' ','<>'),'><',''),'<>',' '),' ','.')
, Amount = LEN(REPLACE(replace(replace(replace(REPLACE(REPLACE(string,'.',''), ',',' '),' ','<>'),'><',''),'<>',' '),' ','.')) - LEN(REPLACE(REPLACE(replace(replace(replace(REPLACE(REPLACE(string,'.',''), ',',' '),' ','<>'),'><',''),'<>',' '),' ','.'),'.','')) + 1
from tbl as t
)
select string,
parsename(EditedString, Amount) as FirstName,
parsename(EditedString, Amount-1) as LastName,
parsename(EditedString, Amount-2) as MiddleInitial
from MyCTE
GO