我有一张这样的表:
Make Model Year
----------------------------------------------------
Toyota Corolla, Camry, Avalon 2009, 2006, 2011
我希望它如下:
Make Model Year
------------------------------
Toyota Corolla 2009
Toyota Camry 2006
Toyota Avalon 2011
基本上我希望将两列分开并按列出的顺序相互关联。
答案 0 :(得分:4)
返回序列的解析函数可以帮助
示例强>
Select A.Make
,B.*
From YourTable A
Cross Apply (
Select Model=B1.RetVal
,Year =B2.RetVal
From [dbo].[tvf-Str-Parse](A.Model,',') B1
Join [dbo].[tvf-Str-Parse](A.Year,',') B2
on B1.RetSeq=B2.RetSeq
) B
<强>返回强>
Make Model Year
Toyota Corolla 2009
Toyota Camry 2006
Toyota Avalon 2011
感兴趣的UDF
CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);