versuchen Sie Folgendes:
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
Sie können den CASE-Befehl verwenden, um zu steuern, ob der Nachname verfügbar ist.
MS SQL Server 2008-Schema-Setup :
Abfrage 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 |
AKTUALISIERT:sqlfiddle hinzugefügt