SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

drpkrupa
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 ,
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
Flowing Fount of Yak Knowledge

USA
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  
 New 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.09 seconds. Powered By: Snitz Forums 2000