如何根据重复多次的分隔符类型将字符串拆分成多个列?

时间:2017-11-08 12:41:01

标签: sql sql-server sql-server-2008 tsql

我想出了如何根据分隔符(在本例中为空格)拆分字符串。

select parsename(replace(replace(replace([Column 0],'  ',' '),'  ',' '),' ','.'), 4) [Date],
parsename(replace(replace(replace([Column 0],'  ',' '),'  ',' '),' ','.'), 3) ID,
parsename(replace(replace(replace([Column 0],'  ',' '),'  ',' '),' ','.'), 2)  Rank1,  
parsename(replace(replace(replace([Column 0],'  ',' '),'  ',' '),' ','.'), 1)   Rank2

--,replace(replace(replace(strCol,'  ',' '),'  ',' '),' ','.') 
from AllData

enter image description here

enter image description here

问题是,我需要基于1到7个分隔符来分割字符串,我认为上面的代码在某些时候将变得难以维护。是否有更优雅的脚本可以帮助我实现我想做的事情?也许表值函数会更好。我不擅长创造这些东西。

感谢所有人。

我正在运行SQL Server 2008。

Drop Table
[Raw_Data_ParsedIDs]

SELECT  DISTINCT
        split.a.value ('/A[1]', 'VARCHAR(MAX)') [Piece1],
          split.a.value ('/A[2]', 'VARCHAR(MAX)') [Piece2],
          split.a.value ('/A[3]', 'VARCHAR(MAX)') [Piece3],
          split.a.value ('/A[4]', 'VARCHAR(MAX)') [Piece4],
          split.a.value ('/A[5]', 'VARCHAR(MAX)') [Piece5],  
          split.a.value ('/A[6]', 'VARCHAR(MAX)') [Piece6],  
          split.a.value ('/A[7]', 'VARCHAR(MAX)') [Piece7]
INTO [Raw_Data_ParsedIDs] 
FROM 
(
SELECT      CAST('<A>' + REPLACE(SrcID, '|', '</A><A>') + '</A>' AS XML) AS Data
FROM  dbo.RAW_DATA_HIST
) a cross apply Data.nodes('/A') AS split(a)

1 个答案:

答案 0 :(得分:1)

您可以使用XML方法拆分字符串:

select    DISTINCT
          split.a.value ('/A[1]', 'VARCHAR(MAX)') [DATA],
          split.a.value ('/A[2]', 'VARCHAR(MAX)') [ID],
          split.a.value ('/A[3]', 'VARCHAR(MAX)') [RANK1],
          split.a.value ('/A[4]', 'VARCHAR(MAX)') [RANK2] from 
(
    SELECT CAST('<A>'+REPLACE(<column>, ' ', '</A><A>')+'</A>' AS XML) AS Data from <table_name>
) a cross apply Data.nodes('/A') AS split(a)

但是,如果要插入已解析的数据,请遵循以下语法: -

INSERT INTO <table_name>
SELECT    DISTINCT
          split.a.value ('/A[1]', 'VARCHAR(MAX)') [Piece1],
          split.a.value ('/A[2]', 'VARCHAR(MAX)') [Piece2],
          split.a.value ('/A[3]', 'VARCHAR(MAX)') [Piece3],
          split.a.value ('/A[4]', 'VARCHAR(MAX)') [Piece4],
          split.a.value ('/A[5]', 'VARCHAR(MAX)') [Piece5],  
          split.a.value ('/A[6]', 'VARCHAR(MAX)') [Piece6],  
          split.a.value ('/A[7]', 'VARCHAR(MAX)') [Piece7]
FROM 
(
SELECT      CAST('<A>' + REPLACE(SrcID, '|', '</A><A>') + '</A>' AS XML) AS Data
FROM  dbo.RAW_DATA_HIST
) a cross apply Data.nodes('/A') AS split(a)