Reputation: 10542
Hey all I have a string that is formatted like so:
Bob Barker - The Game Show Host
Bill Gates - A Programmer
Steve Jobs - The Apple Guy
The above is in a row called rowNameOcu.
What I am looking to do is query that and present it like this:
Barker, Bob - The Game Show Host
Gates, Bill - A Programmer
Jobs, Steve - The Apple Guy
I am sure I could look for the - and then grab everything to the right of that, but then how can I reverse the name after that?
Any help would be great!
Upvotes: 0
Views: 104
Reputation: 36
Here's an option:
SELECT
SUBSTRING(rowNameOcu,CHARINDEX(' ',rowNameOcu),CHARINDEX(' ',right(rowNameOcu,len(rowNameOcu) - CHARINDEX(' ',rowNameOcu)))) + ', ' + left(rowNameOcu,CHARINDEX(' ',rowNameOcu)) + RIGHT(rowNameOcu, CHARINDEX('-',reverse(rowNameOcu)))
FROM MyTable
Upvotes: 2
Reputation: 175596
You can use CHARINDEX
and SUBSTRING
:
Declare @t table ( [Name] varchar(100) );
insert into @t ( Name )
VALUES ( 'Bob Barker - The Game Show Host' ),
('Bill Gates - A Programmer'),
('Steve Jobs - The Apple Guy') ;
;WITH cte AS
(SELECT
[Name],
[Title] = CASE WHEN CHARINDEX('-', [Name]) > 0 THEN
SUBSTRING([Name],CHARINDEX('-',[Name])+1, ( LEN([Name]) - CHARINDEX(' ',[Name])+1) )
ELSE NULL
END,
[FIRST_NAME] = CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
LEFT([Name],CHARINDEX(' ',[Name])-1)
ELSE[Name]
END,
[LAST_NAME] = CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
SUBSTRING([Name],CHARINDEX(' ',[Name])+1, (CHARINDEX('-',[name]) - CHARINDEX(' ', [name])-1) )
ELSE NULL
END
FROM @t
)
SELECT [Last_Name] + ', ' + [First_Name] + ' - ' + [Title]
FROM cte;
Warning: They may be edge cases when it fails like 3 part name or title with -
Upvotes: 0