我在列中有一个长字符串作为员工的全名,我想用名字,中间名和姓氏打破它。例如我有Andrade, Maria Sandra
(lname,(空格)fname(空格)mname)打破就好了
fname = Maria,lname = Andrade和Sandra这样的中间名。
我的专栏通常有lname,fname。
我可以分割lname,但不能正确分解fname和mname
SELECT EmployeeName as [full name ], SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)) as[First name ]
,SUBSTRING( EmployeeName,0,CHARINDEX(',',EmployeeName)) [Last Name]
, SUBSTRING( SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)),CHARINDEX(' ',EmployeeName),LEN (SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName),LEN(EmployeeName)))) as[Middle name ]
FROM test$`
答案 0 :(得分:1)
以下是您应该对数据进行规范化的完美原因。
declare @table table(thename varchar(500))
insert into @table
values
('Andrade, Maria Sandra'),
('Andrade, Maria'),
('Andrade, Maria Sandra OhSnap')
select
left(thename,CHARINDEX(',',thename) - 1) as LastName
,substring(thename,charindex(' ',thename),case when charindex(' ',thename) + charindex(' ',reverse(thename)) > len(thename) then charindex(' ',reverse(thename)) else len(thename) - (charindex(' ',thename) + charindex(' ',reverse(thename))) + 1 end) as FirstName
,case when charindex(' ',thename) + charindex(' ',reverse(thename)) - 1 = len(thename) then null else right(thename,charindex(' ',reverse(thename))) end as MiddleName
from @table