Home All Groups Group Topic Archive Search About

Splitting name column into seperate columns

Author
19 May 2006 3:57 PM
M Stuart
I would like to split a Name column which holds the full name with spaces
into 3 seperate columns. ie Title, Firstname, Surname.

Regards

Mike

Author
19 May 2006 4:07 PM
--CELKO--
This can be trickier than you think.   ""Herr Doktor Johan van der
Poon" is a nightmare for simple SQL statements.

But for a quickie, google up some old posts on comma separated list and
modify the code.
Author
19 May 2006 4:10 PM
Anith Sen
First, look up the string functions like CHARINDEX and SUBSTRING in SQL
Server Books Online. If you have difficulty in creating an expression to
split the value, then post back.

--
Anith
Author
19 May 2006 4:16 PM
Omnibuzz
I hate this solution.
I would suggest you keep it as three seperate columns.
But there might be constraints on design change.. I understand :)
So here is the solution anyways.. I guess you can change the variable to the
column name

declare @name varchar(20)
set @name = 'asc dsds fdfdd'

select left(@name, charindex(' ',@name)) as firstname,
reverse(left(reverse(@name),charindex(' ',reverse(@name)))) as lastname,
left(left(@name, charindex(' ',@name)),charindex(' ',left(@name, charindex('
',@name)))) as middlename

Hope this helps.
Author
19 May 2006 4:22 PM
Omnibuzz
change.. sorry

declare @name varchar(20)
set @name = 'asc dsds fdfdd'

select left(@name, charindex(' ',@name)) as firstname,
reverse(left(reverse(@name),charindex(' ',reverse(@name)))) as lastname,
substring(@name,charindex(' ',@name),charindex(' ',@name,charindex('
',@name) + 1) - charindex(' ',@name)) as middlename
Author
19 May 2006 4:22 PM
Mark Williams
/*untested*/
SELECT RTRIM(LEFT(Name, CHARINDEX(' ', Name))),
SUBSTRING(Name, CHARINDEX(' ', Name) + 1, LEN(Name) - CHARINDEX(' ',
REVERSE(Name)) - 1),
RIGHT(Name, CHARINDEX(' ', REVERSE(Name)) - 1)
FROM [Your Table]

And what CELKO said, this all falls apart when name with more that two
spaces occurs.


--


Show quote
"M Stuart" wrote:

> I would like to split a Name column which holds the full name with spaces
> into 3 seperate columns. ie Title, Firstname, Surname.
>
> Regards
>
> Mike

AddThis Social Bookmark Button