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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query help
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Yak Posting Veteran

74 Posts

Posted - 09/29/2006 :  13:14:20  Show Profile  Reply with Quote
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 ,

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

Flowing Fount of Yak Knowledge

1837 Posts

Posted - 09/29/2006 :  13:28:28  Show Profile  Reply with Quote
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

Edited by - snSQL on 09/29/2006 13:39:54
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000