【问题标题】:How to move the data to the next line based on spaces in sqlserver 2008 R2sql server 2008 R2中如何根据空格将数据移动到下一行
【发布时间】:2017-12-07 06:44:26
【问题描述】:

输入:如果单词到单词的空间是3个空格并且单词的长度是>9,则将列值保留到下一行。

declare @Table table(CL1 varchar(50))
    INSERT INTO @Table
    SELECT 'Ohh   my GOD'
    UNION ALL
    SELECT 'hindunewspaer is no1 paper'

select * from @Table

o/p:

CL1

ohh
my god
hindunewpaer
is no1 paper

【问题讨论】:

    标签: tsql sql-server-2012 sql-server-2008-r2


    【解决方案1】:

    使用了拆分/解析功能。如果需要,可以内联。

    EDIT - 切换到不限于 8K 的 Parser,因为最终 字符串很容易大于 8K

    示例

    ;with cte0 as (
            Select Seq=Row_Number() over (Order by (Select null)),RetSeq,RetVal
             From  @Table A
             Cross Apply ( 
                          Select RetSeq
                                ,RetVal=case when len(RetVal)>9 then '~~~' else '' end+RetVal+case when len(RetVal)>9 then '~~~' else '' end
                           From  [dbo].[udf-Str-Parse](Replace(CL1,'   ','~~~ '),' ') 
                        ) B ),
          cte1 as ( Select S=Stuff((Select ' '+RetVal From  cte0 Order by Seq For XML Path ('')),1,1,'') )                   
    Select CL1 = RetVal
     From  cte1 A
     Cross Apply [dbo].[udf-Str-Parse](A.S,'~~~') B
     Order By RetSeq
    

    退货

    CL1
    Ohh
    my GOD
    hindunewspaer
    is no1 paper
    

    必要时的拆分/解析功能

    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((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)
    );
    --Thanks Shnugo for making this XML safe
    --Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
    --Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
    --Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多