essayez ceci :
select
case when CHARINDEX('_',name)>0
then SUBSTRING(name,1,CHARINDEX('_',name)-1)
else name end firstname,
CASE WHEN CHARINDEX('_',name)>0
THEN SUBSTRING(name,CHARINDEX('_',name)+1,len(name))
ELSE NULL END as lastname
from emp
vous pouvez utiliser la commande CASE pour contrôler si le nom de famille est disponible.
Configuration du schéma MS SQL Server 2008 :
Requête 1 :
declare @t table (id int, name varchar(50))
insert into @t (id,name) values( 1 ,'abc_rao')
insert into @t (id,name) values( 2 ,'nani')
insert into @t (id,name) values( 3 ,'hari_babu')
insert into @t (id,name) values( 4 ,'kalibabu')
insert into @t (id,name) values( 5 ,'ab_tan')
select
case when CHARINDEX('_',name)>0
then SUBSTRING(name,1,CHARINDEX('_',name)-1)
else name end firstname,
CASE WHEN CHARINDEX('_',name)>0
THEN SUBSTRING(name,CHARINDEX('_',name)+1,len(name))
ELSE NULL END as lastname
from @t
| FIRSTNAME | LASTNAME |
|-----------|----------|
| abc | rao |
| nani | (null) |
| hari | babu |
| kalibabu | (null) |
| ab | tan |
MISE À JOUR :sqlfiddle ajouté