开发者社区 问答 正文

析字符串中间的文本-SQL Server

我在一个字符串中有几百行,看起来像这样:


filler|filler|scrape this text|and this text|sometimes this to|filler|filler

是否可以仅选择第二个|之后的文本?在最后2个| s之前?

展开
收起
Puppet 2020-01-04 11:42:23 470 分享 版权
1 条回答
写回答
取消 提交回答
  • 由于您使用的是2016年版本,因此可以选择string_split(),但该订单没有GTD。也就是说,考虑一下XML

    
    Declare @YourTable Table ([ID] int,[SomeCol] varchar(150))
    Insert Into @YourTable Values 
    (1,'filler|filler|scrape this text|and this text|sometimes this to|filler|filler')
    
    Select A.ID 
          ,B.Pos3
          ,B.Pos4 
          ,B.Pos5
     From @YourTable A
     Cross Apply (
                    Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                          ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                          ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                          ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                          ,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
                          ,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
                          ,Pos7 = ltrim(rtrim(xDim.value('/x[7]','varchar(max)')))
                    From  ( values (cast('<x>' + replace((Select replace(SomeCol,'|','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml)))  A(xDim)
                 ) B
    

    退货

    ID  Pos3                Pos4            Pos5
    1   scrape this text    and this text   sometimes this to
    
    2020-01-04 11:42:52
    赞同 展开评论