如何从下面转换数据:
CODE COMBINATION USER 1111.111.11.0 KEN; JIMMY 666.778.0.99 KEN 888.66.77.99 LIM(JIM); JIMMY
至
CODE COMBINATION USER 1111.111.11.0 KEN 1111.111.11.0 JIMMY 666.778.0.99 KEN 888.66.77.99 LIM(JIM) 888.66.77.99 JIMMY
解决方法
使用此TVF,您可以提供要拆分的字符串和分隔符.此外,您可以获得对二次处理非常有用的序列号.
Select [CODE COMBINATION],[USER] = B.RetVal From YourTable A Cross Apply [dbo].[udf-Str-Parse](A.[USER],';') B
返回
The Parse UDF
CREATE FUNCTION [dbo].[udf-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(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A Cross Apply x.nodes('x') AS B(i) ); --Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',') --Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
现在,另一个选项是Parse-Row UDF.请注意,我们将解析后的字符串返回到一行.目前有9个职位,但很容易扩大或缩小.
Select [CODE COMBINATION],B.* From YourTable A Cross Apply [dbo].[udf-Str-Parse-Row](A.[USER],';') B
返回
The Parse Row UDF
CREATE FUNCTION [dbo].[udf-Str-Parse-Row] (@String varchar(max),@Delimiter varchar(10)) Returns Table As Return ( Select Pos1 = xDim.value('/x[1]','varchar(max)'),Pos2 = xDim.value('/x[2]',Pos3 = xDim.value('/x[3]',Pos4 = xDim.value('/x[4]',Pos5 = xDim.value('/x[5]',Pos6 = xDim.value('/x[6]',Pos7 = xDim.value('/x[7]',Pos8 = xDim.value('/x[8]',Pos9 = xDim.value('/x[9]','varchar(max)') From (Select Cast('<x>' + Replace(@String,'</x><x>')+'</x>' as XML) as xDim) A ) --Select * from [dbo].[udf-Str-Parse-Row]('Dog,') --Select * from [dbo].[udf-Str-Parse-Row]('John Cappelletti',' ')