Question: I have this column

```
NAME
John Stephenson
James Martin
Anna Corelia

```

How I can select this column to this?

```
NAME
Stephenson, John
Martin, James
Corelia, Anna 

```

Answer: 
One way

```
;with test(name) as (
    select 'John Stephenson' union all
    select 'James Martin' union all
    select 'Anna J. Corelia' union all
    select 'BOBBYTABLES'
)
select
case when charindex(' ', name) = 0 then name  
else right(name, charindex(' ', reverse(name)) - 1) + ', ' + substring(name, 1, len(name) - charindex(' ', reverse(name))) end
from test

(No column name)
Stephenson, John
Martin, James
Corelia, Anna J.
BOBBYTABLES

```
Here is a solution including how I got the final output column.

This will handle three part names, like "Rip Van Winkle", also names with no white space and will strip (trim) any leading/trailing white space from the names.

```
DECLARE @NAMES TABLE (NAME NVARCHAR(MAX))
INSERT INTO @NAMES (NAME) VALUES ('John Stephenson'),('James Martin'),('Anna Corelia'),('Rip Van Winkle'),('Sally')

SELECT *, 
       CHARINDEX(' ',LTRIM(RTRIM(NAME))) [SpaceLocation],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN RIGHT(LTRIM(RTRIM(NAME)), LEN(LTRIM(RTRIM(NAME)))-CHARINDEX(' ',LTRIM(RTRIM(NAME)))) END [LastName],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN LEFT(LTRIM(RTRIM(NAME)),CHARINDEX(' ',LTRIM(RTRIM(LTRIM(RTRIM(NAME)))))-1) END [FirstName],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN RIGHT(LTRIM(RTRIM(NAME)), LEN(LTRIM(RTRIM(NAME)))-CHARINDEX(' ',LTRIM(RTRIM(NAME)))) + ', ' +LEFT(LTRIM(RTRIM(NAME)),CHARINDEX(' ',LTRIM(RTRIM(NAME)))-1) ELSE LTRIM(RTRIM(NAME)) END [FinalOutput]
FROM @NAMES

```