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.
views:
63answers:
4
A:
You've not mentioned the DB. You can try something like in MySQL:
SELECT SUBSTRING(name,LOCATE(",",name)+1)
FROM TABLE_NAME
codaddict
2010-09-20 09:28:49
Like that but the 'WHERE' lost an E in translation and became WHRE
Woody
2010-09-20 09:31:26
I think he also wants to extract the last name only but the function to use depends on his DBMS
vc 74
2010-09-20 09:32:56
Khan is just an example.this will give all the names ending with ,khan. I want only lastname from the column name
NayeemKhan
2010-09-20 09:37:02
my DB is SQL server 2005
NayeemKhan
2010-09-20 09:49:24
+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
2010-09-20 09:36:40
Its giving output as it is. as per my example o/p is still Nayeem,Khan.
NayeemKhan
2010-09-20 10:11:25
Try reversing the ',' and name arguments in the CHARINDEX function, as I've done in my example
Mark Baker
2010-09-20 10:24:15
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
2010-09-20 09:39:38
I would also suggest trimming each substr result in case there are spaces before/after the comma
JohnoBoy
2010-09-20 09:41:57
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
2010-09-20 09:59:05
+1
A:
Here a postgreSQL solution :
SELECT SUBSTRING(name from ',(.+)$') FROM table;
SELECT SUBSTRING('foo,bar' from ',(.+)$') ;
substring
-----------
bar
(1 row)
M42
2010-09-20 09:46:40
its saying- Incorrect syntax near the keyword 'from'. i am using sql server 2005
NayeemKhan
2010-09-20 09:58:56
It's for postgreSQL, i don't know SQL Server. But may be there is some similar function.
M42
2010-09-20 10:08:21