Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query help

Author  Topic 

drpkrupa
Yak Posting Veteran

74 Posts

Posted - 2006-09-29 : 13:14:20
I have a column called name which is combination of first name and last name with ,
Now i also have commercial name which does not has ,
Like

Mike, Shey
Peter, Fermondoz
The New Dora Mb Church

I want a seprate first name and last name i wrote this is it failed because for third name(without ,)

select substring(name,1,charindex(',',name)-1) as lastname
, substring(name,charindex(',',name)+2,len(name)) as firstname
from account

how can i run this query and if no last name then display null
result needed:
First Last
Mike Shey
Peter Fermondoz
The New Dora Mb Church

snSQL
Master Smack Fu Yak Hacker

1837 Posts

Posted - 2006-09-29 : 13:28:28
You really should redesign this table to hold firstname, lastname, and commercial name in separate columns. And actually you should go a step further and create two separate tables one for people and one for companies - have a look on this site for articles about normalization for more about that.

But, that said, here you go:


select CASE WHEN charindex(',',[name]) > 0
THEN substring([name], 1, charindex(',',[name])-1)
ELSE [name]
END as lastname
, CASE WHEN charindex(',',[name]) > 0
THEN substring([name], charindex(',',[name])+2, len([name]))
ELSE ''
END as firstname
from account
Go to Top of Page
   

- Advertisement -