将分号分隔符SQL拆分为行

时间:2017-02-02 10:01:10

标签: sql sql-server csv split

只想寻求帮助。 我试图用分号作为分隔符来分割分隔值。 由于存在逗号值,因此无法将逗号替换为分号。

ID   Value
1   | A&B;C;D;E, F

转换为:

ID   Value
1    A&B
1    C
1    D
1    E, F

我尝试调整我上网的SQL脚本但没有成功

SELECT F1.ID,
 O.splitdata 
FROM
 (
 SELECT OldID,
 cast('<X>'+replace((SELECT ColumnName + '' FOR XML PATH('')),';','</X><X>')+'</X>' as XML) as xmlfilter from TableName F
 )F1
 CROSS APPLY
 ( 
 SELECT fdata.D.value('.','varchar(max)') as splitdata 
 FROM f1.xmlfilter.nodes('X') as fdata(D)) O

它适用于我的一些列,但如果列有特殊或非法字符,则会输出此错误:

Msg 9411, Level 16, State 1, Line 2
XML parsing: line 1, character 16, semicolon expected

谢谢!

3 个答案:

答案 0 :(得分:1)

带有UDF的选项1

Declare @YourTable table (ID int, Value varchar(max))
Insert Into @YourTable values
(1,'A&B;C;D;E, F')

Select A.ID
      ,B.*
 From @YourTable A
 Cross Apply [dbo].[udf-Str-Parse-8K](A.Value,';') B

没有UDF的选项2

Select A.ID
      ,B.*
 From @YourTable A
 Cross Apply (
                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(A.Value,';','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
                Cross Apply x.nodes('x') AS B(i)
              ) B

返回

ID  RetSeq  RetVal
1   1       A&B
1   2       C
1   3       D
1   4       E, F

此UDF是XML安全且非常快

CREATE FUNCTION [dbo].[udf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table 
As
Return (  
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Much faster than str-Parse, but limited to 8K
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')

答案 1 :(得分:1)

如果您不喜欢某个功能,或者您没有创建新功能的权限,则可以使用相当快的XML方法。在您的情况下,需要一些额外的努力才能使这个XML安全(由于特殊字符和;作为分隔符):

Declare @Dummy table (ID int, SomeTextToSplit varchar(max))
Insert Into @Dummy values
 (1,'A&B;C;D;E, F')
,(2,'"C" & "D";<C>;D;E, F');

DECLARE @Delimiter VARCHAR(10)=';';
WITH Casted AS
(
    SELECT *
          ,CAST('<x>' + REPLACE((SELECT REPLACE(SomeTextToSplit,@Delimiter,'§§Split$me$here§§') AS [*] FOR XML PATH('')),'§§Split$me$here§§','</x><x>') + '</x>' AS XML) AS SplitMe
    FROM @Dummy
)
SELECT Casted.*
      ,x.value('.','nvarchar(max)') AS Part 
FROM Casted
CROSS APPLY SplitMe.nodes('/x') AS A(x)

结果

1   A&B
1   C
1   D
1   E, F
2   "C" & "D"
2   <C>
2   D
2   E, F

答案 2 :(得分:0)

请使用以下函数按特定分隔符分割字符串:

CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))        
returns @temptable TABLE (SplitValue varchar(8000))        
as        
begin        
    declare @idx int        
    declare @slice varchar(8000)        

    select @idx = 1        
       if len(@String)<1 or @String is null  return        

    while @idx!= 0        
    begin        
        set @idx = charindex(@Delimiter,@String)        
        if @idx!=0        
            set @slice = left(@String,@idx - 1)        
        else        
            set @slice = @String        

        if(len(@slice)>0)   
            insert into @temptable(SplitValue) values(@slice)        

        set @String = right(@String,len(@String) - @idx)        
        if len(@String) = 0 break        
    end    
return       
end

如果您有任何疑问,请与我们联系。

谢谢。