我有下表
AdviserName
-----------
Tearle, Michael Hearn
Hearn Tearle, Michael
Van Der Welden, Luke
Welden, Luke Van Der
Brennan, Sony G
G Brennan, Sony
Rhammasamysundaran, Vishnu Brahma Kuma
Brahma Kuma Rhammasamysundaran, Vishnu
基本上我需要重新安排,所以它成为FirstName MiddleName LastName。例如Michael Hearn Tearle或Sony G Brennan或Luke Van Der Welden。
我使用了下面的语法但不知何故它不喜欢中间名是否像Hearn Tearle,Michael这样的逗号。
If(OBJECT_ID('tempdb..#tempX') Is Not Null)
Drop Table #tempX
create table #tempX (AdviserName varchar(max))
insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')
--select * from #tempX
select substring(advisername, charindex(',', replace(advisername, ' ', '')) + 1, len(advisername))+' '+ left(advisername, charindex(',', advisername) -1) as AdviserName from #tempX
以下是结果。
AdviserName
--------------------------------------
Michael Hearn Tearle
, Michael Hearn Tearle
n, Luke Van Der Welden
Luke Van Der Welden
Sony G Brennan
, Sony G Brennan
Vishnu Brahma Kuma Rhammasamysundaran
n, Vishnu Brahma Kuma Rhammasamysundaran
如何在逗号之前和逗号之后进行查询以满足中间名?
我正在使用SQL Server 2012.
谢谢大家。
答案 0 :(得分:1)
试试这个
If(OBJECT_ID('tempdb..#tempX') Is Not Null)
Drop Table #tempX
create table #tempX (AdviserName varchar(max))
insert into #tempX (AdviserName)
values ('Tearle, Michael Hearn'),('Hearn Tearle, Michael'),('Van Der Welden, Luke'),('Welden, Luke Van Der'),('Brennan, Sony G'),('G Brennan, Sony'),('Rhammasamysundaran, Vishnu Brahma Kuma '), ('Brahma Kuma Rhammasamysundaran, Vishnu ')
select
AdviserName,
replace(replace(
SUBSTRING(AdviserName,charindex(',',AdviserName),len(AdviserName))
+' '+
SUBSTRING(AdviserName,1,charindex(',',AdviserName))
,',',''),' ',' ')
from #tempX
答案 1 :(得分:1)
;with d as
(select AdviserName, charindex(',',AdviserName) as comma from #tempX)
select
ltrim(rtrim(substring(advisername,comma+1,100)))+' '+ltrim(rtrim(left(advisername,comma-1)))
from d