使用SQL Server拆分姓氏和名字

时间:2015-09-11 00:13:13

标签: sql sql-server tsql

我的列中包含以下值:

Full Name
----------------
X-y, z C
CLOSE, Test G.
CMN, DEV S.
Micheal Land

我需要以下列方式输出

Last_Name   First_Name  Middle-Name
-----------------------------------
X-y            Z              C
CLOSE          Test           G
CMN            DEV            S

Micheal Land

1 个答案:

答案 0 :(得分:1)

Create table #temp ([Full Name] varchar(100))

insert into #temp
select 'X-y, z C'
union all 
select 'CLOSE, Test G.'
Union all
select 'CMN, DEV S.'
union all
select 'Micheal Land'
UPDATE #temp SET [Full Name]=REPLACE([Full Name],', ',',')
select  substring([Full Name],0,CASE CHARINDEX(',',[Full Name]) WHEN 0 THEN LEN([Full Name]) ELSE CHARINDEX(',',[Full Name])  END ) Last_Name,
CASE CHARINDEX(',',[Full Name]) WHEN 0 THEN '' ELSE substring([Full Name],CHARINDEX(',',[Full Name])+1,-CHARINDEX(',',[Full Name])+CHARINDEX(' ',[Full Name])) END First_Name,
CASE CHARINDEX(',',[Full Name]) WHEN 0 THEN '' ELSE substring([Full Name],CHARINDEX(' ',[Full Name])+1,LEN([Full Name])) END [Middle-Name] from #temp