在SQL Server中将一列拆分为多列

时间:2018-03-24 17:06:52

标签: arrays sql-server string split

我有一个名为Employee的表,其中包含以下列:

FullName
--------------------
Holmes, John Henry

我想更改表格并将FullName转为LastNameFirstNameMiddleName。我应该使用哪些SQL命令来实现这一目标?我希望得到的结果是:

LastName    FirstName    MiddleName
-----------------------------------
Holmes      John         Henry

我已经尝试过youtube视频,论坛和文章,但无济于事。

任何帮助都会非常感激,因为我刚开始使用SQL。

2 个答案:

答案 0 :(得分:1)

假设您正在使用SQL Server(如标题中所述),您可以使用以下查询将全名拆分为last,first和middle:

select substring(FullName, 1, patindex('%,%', FullName) - 1) as LastName,
substring(
  FullName, 
  charindex(', ', FullName) + 2, 
  charindex(' ', FullName, charindex(', ', FullName) + 2) - charindex(', ', FullName) - 2) as FirstName,
substring(FullName, charindex(' ', FullName, charindex(', ', FullName) + 2) + 1, charindex(' ', FullName, -1)) as MiddleName
from Employee;

这将输出:

LastName  |  FirstName  |  MiddleName
-------------------------------------
  Holmes  |       John  |       Henry

请尝试:http://sqlfiddle.com/#!18/e78fc/1

<强> [编辑]
要更新现有表,以便将全名保存为last,first和middle,您需要:

(1)通过添加FirstName,MiddleName和LastName列来改变表:

alter table Employee 
add FirstName varchar(50), 
    MiddleName varchar(50),
    LastName varchar(50);

(2)通过将全名分为last,first和middle来更新表:

update Employee
set FirstName = substring(
    FullName, 
    charindex(', ', FullName) + 2, 
    charindex(' ', FullName, charindex(', ', FullName) + 2) - charindex(', ', FullName) - 2),
  MiddleName = substring(FullName, charindex(' ', FullName, charindex(', ', FullName) + 2) + 1, charindex(' ', FullName, -1)),
  LastName = substring(FullName, 1, patindex('%,%', FullName) - 1);

(3)删除FullName列:

alter table Employee drop column FullName;

你可以在sqlfiddle上试试上面的sql:http://sqlfiddle.com/#!18/a418d/2

答案 1 :(得分:0)

SELECT SUBSTRING_INDEX(Fullname,',',1) AS Last_Name,
SUBSTRING_INDEX(SUBSTRING_INDEX(Fullname,' ',-2),' ',1)AS First_Name,
SUBSTRING_INDEX(SUBSTRING_INDEX(Fullname,' ',-1),' ',1) AS Middle_Name
FROM table1;

输出

Last_Name   First_Name  Middle_Name
Holmes      John        Henry

现场演示

  

http://sqlfiddle.com/#!9/5ec9f8/9