我对sql Server有一个小问题,请告诉我如何解决这个问题
表:emp
id name --------------- 1 abc_rao 2 nani 3 hari_babu 4 kalibabu 5 ab_tan
根据该表我想要输出如下
id firstname lastname 1 abc rao 2 nani nothing 3 hari babu 4 kalibabu nothing 5 ab tan
我试过这样的:
select SUBSTRING(name,1,CHARINDEX('_',name) - 1) as firstname,SUBSTRING(name,name) + 1,LEN(name)) as lastname from emp
但我没有得到完全预期的结果.
相反,我收到一个错误:
Msg 537,Level 16,State 2,Line 3
Invalid length parameter passed to the LEFT or SUBSTRING function.
请告诉我如何解决这个问题
解决方法
尝试这个:
select case when CHARINDEX('_',name)>0 then SUBSTRING(name,name)-1) else name end firstname,CASE WHEN CHARINDEX('_',name)>0 THEN SUBSTRING(name,name)+1,len(name)) ELSE NULL END as lastname from emp
您可以使用CASE命令来控制可用的姓氏.
MS sql Server 2008架构设置:
查询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('_',len(name)) ELSE NULL END as lastname from @t
| FIRSTNAME | LASTNAME | |-----------|----------| | abc | rao | | nani | (null) | | hari | babu | | kalibabu | (null) | | ab | tan |