views:

63

answers:

4

In SQL, suppose i have a table employee and have a column as Name containing all the names in the format FirstName,LastName. Ex:Nayeem,Khan . I want to fetch all the last names only ie Khan.

A: 

You've not mentioned the DB. You can try something like in MySQL:

SELECT SUBSTRING(name,LOCATE(",",name)+1)
FROM TABLE_NAME
codaddict
Like that but the 'WHERE' lost an E in translation and became WHRE
Woody
I think he also wants to extract the last name only but the function to use depends on his DBMS
vc 74
Khan is just an example.this will give all the names ending with ,khan. I want only lastname from the column name
NayeemKhan
my DB is SQL server 2005
NayeemKhan
+1  A: 

ORACLE or MySQL solution

select DISTINCT SUBSTR(name,INSTR(name,',')+1)
  from employee

EDIT

For SQL Server, try

select SUBSTRING(name,CHARINDEX(',',name)+1,999) 
  from employee 

assumes that name will always contain a ,

Mark Baker
Its giving output as it is. as per my example o/p is still Nayeem,Khan.
NayeemKhan
Try reversing the ',' and name arguments in the CHARINDEX function, as I've done in my example
Mark Baker
Its working!! tal
NayeemKhan
A: 

In oracle, that would be

select substr(name, 1, instr(name. ',') - 1) as first_name,
       substr(name, instr(name. ',') + 1) as last_name
from TABLE_NAME
JohnoBoy
I would also suggest trimming each substr result in case there are spaces before/after the comma
JohnoBoy
kindly give solution for SQL server 2005 DB
NayeemKhan
If you'd wanted SQL server 2005 DB, it would have been better if you'd let us know that right from the start
Mark Baker
now u came to know right.. Give solution now
NayeemKhan
+1  A: 

Here a postgreSQL solution :

SELECT SUBSTRING(name from ',(.+)$') FROM table;


SELECT SUBSTRING('foo,bar' from ',(.+)$') ;
 substring
-----------
 bar
(1 row)
M42
its saying- Incorrect syntax near the keyword 'from'. i am using sql server 2005
NayeemKhan
It's for postgreSQL, i don't know SQL Server. But may be there is some similar function.
M42
thanks.. no problem
NayeemKhan