tsql – SQL Server:将字符串拆分为行

前端之家收集整理的这篇文章主要介绍了tsql – SQL Server:将字符串拆分为行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何从下面转换数据:
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

我知道在sql Server 2016中这可以通过分割字符串函数来完成,但我的作品是sql Server 2014.

解决方法

使用此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',' ')

猜你在找的MsSQL相关文章