我需要在SQL Server中拆分以下字符串:
'1:1:0:0:1231,1:0:0:0101:1231'
首先,我需要分成两行:
最后,我必须使用以下名称将每一行拆分为不同的列:
isactive--|--year--|--anniversay--|--startperiod--|--endperiod
1 1 0 0 1231
1 0 0 0101 1231
我有以下分割功能,但它只适用于第一次分割(,),因为它不适用于列。
CREATE FUNCTION [dbo].[Split]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
GO
有任何线索吗?
答案 0 :(得分:1)
两次应用此功能怎么样?第二次需要将值重新聚合到新行中。类似的东西:
select r.*
from t cross apply
(select data
from split(t.col, ';')
) di cross apply
(select max(case when did.id = 1 then did.data end) as isactive,
max(case when did.id = 2 then did.data end) as year,
max(case when did.id = 3 then did.data end) as anniversary,
max(case when did.id = 4 then did.data end) as startperiod,
max(case when did.id = 5 then did.data end) as endperiod
from split(di.data) did
) r;