使用SQL Server将名称和标题分隔为单独的列

时间:2017-01-18 18:46:51

标签: sql sql-server

我构建了SQL Server代码,它将第一个名字,姓氏,中间名首字母和标题作为单独的项目从一个表格中提取,但是当没有中间的首字母时,我遇到了问题:

工作:

DOE,JOHN A MD - 

Last name: DOE
First name: JOHN
Middle initial:A
Title: MD

不工作:

DOE,JOHN MD -

Last name: DOE
First name: JOHN
Middle initial: M
Title: D

我目前正在使用的代码:

ISNULL(CASE  
          WHEN 0 = CHARINDEX(' ', RIGHT(Name, LEN(Name), CHARINDEX(',', Name))) 
             THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)) 
          ELSE SUBSTRING(RIGHT(Name, LEN(Name) - CHARINDEX(',', Name)), 1, CHARINDEX(' ', RIGHT(Name, LEN(Name) - CHARINDEX(',', Name))) - 1)
       END, '') AS FirstName,
ISNULL(CASE 
          WHEN 0 = CHARINDEX(' ', RIGHT(Name, LEN(Name) - CHARINDEX(',', Name))) 
             THEN NULL 
             ELSE SUBSTRING(RIGHT(Name, LEN(Name) - CHARINDEX(',', Name)), CHARINDEX(' ', RIGHT(Name, LEN(Name) - CHARINDEX(',', Name))) + 1, 1) 
       END,'') as MiddleInitial,
ISNULL(CASE 
          WHEN 0 = CHARINDEX(' ', SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1)) 
             THEN SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) 
             ELSE SUBSTRING(SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1), 1, CHARINDEX(' ', SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1)) - 1) 
       END,'') as LastName,
ISNULL(CASE 
          WHEN 0 = CHARINDEX(' ', RIGHT(Name, LEN(Name) - CHARINDEX(',', Name))) 
             THEN NULL 
             ELSE SUBSTRING(RIGHT(Name, LEN(Name) - CHARINDEX(',', Name)), CHARINDEX(' ', RIGHT(Name, LEN(Name) - CHARINDEX(',', Name))) + 2, 4)
       END,'') as Spec,
ISNULL(ProviderID, ' ') as provid,
ISNULL(ServiceID,' ') as svcid,
ISNULL(SpecialtyAbsServiceID,' ') sabsid

非常感谢任何帮助!

谢谢 - 马特

1 个答案:

答案 0 :(得分:2)

这是一个解析名称的滑坡,但这可能会有所帮助。

它适用于样本数据,但多字名称将是一个问题。例如 Betty Jane 作为First Name

Declare @YourTable table (ID int,Name varchar(50))
Insert Into @YourTable values
(1,'DOE,JOHN A MD'),
(2,'DOE,JOHN MD')

Select A.*
      ,Last_Name   = B.Pos1
      ,First_Name  = B.Pos2
      ,Middle_Name = case when B.Pos4 is null then '' else B.Pos3 end
      ,Title       = case when B.Pos4 is null then B.Pos3 else B.Pos4 end
 From @YourTable A
 Cross Apply (
                Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                      ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                      ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                      ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                From  (Select Cast('<x>' + replace((Select Replace(Replace(A.Name,',',' '),'  ',' ') as [*] For XML Path('')),' ','</x><x>')+'</x>' as xml) as xDim) as A 
             ) B

返回

ID  Name            Last_Name   First_Name  Middle_Name Title
1   DOE,JOHN A MD   DOE         JOHN        A           MD
2   DOE,JOHN MD     DOE         JOHN                    MD