将列字符串数据分成许多列SQL

时间:2019-03-27 19:08:40

标签: sql-server tsql

如何将一个列字符串值分成多个列。假设我有一个名为“ John Bob UnderWood JR”的行,另一个名为“ Sally Woods Feld”的行,有人可以帮我举例吗?我在处理名称超过两个值的子字符串和CHARINDEX时遇到问题。在下面,我将其用于两个名称字段,但不确定如何继续使用两个以上的名称。

SELECT substring(Username, 1, CHARINDEX(' ',Username)-1) FirstName, 
substring(Username, CHARINDEX(' ',Username)+1, LEN(Username)) LastName 
FROM tblName

我也使用过:

Select parsename(Replace(name_ind, ' ', '.'), 3) as LastName,
parsename(Replace(name_ind, ' ', '.'), 2) as FirstName,
parsename(Replace(name_ind, ' ', '.'), 1) as MiddleName,
parsename(Replace(name_ind, ' ', '.'), 4) as Suffix
from UspfoWeb.dbo.tbl_pers_svcmbr_tbl_go;

我想看哪个输出,但是当名称中有后缀时,它会进入姓氏位置,并且如果只有两个名称,则它们的姓氏会进入中间名称列。我假设我需要创建一个if语句对它们进行正确排序?

预期结果:

firstName    lastname   middleName   Suffix
John         Bob        Underwood    Jr.
Sally        Woods      Feld

1 个答案:

答案 0 :(得分:0)

您可以在类似的行上使用以下代码。

GO
CREATE FUNCTION dbo.SplitStrings
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS @Tab TABLE(ID INT IDENTITY,Item NVARCHAR(10))  
AS
BEGIN
      INSERT INTO @Tab(Item)   
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   RETURN;
END
GO

SELECT *
,
(SELECT Item
FROM dbo.SplitStrings(UserName,' ')
WHERE ID = 1) AS [First Name]
,
(SELECT Item
FROM dbo.SplitStrings(UserName,' ')
WHERE ID = 2) AS [Last Name]
,
(SELECT Item
FROM dbo.SplitStrings(UserName,' ')
WHERE ID = 3) AS [Middle Name]
,   
(SELECT Item
FROM dbo.SplitStrings(UserName,' ')
WHERE ID = 4) AS [Suffix]
FROM UserTable