zoukankan      html  css  js  c++  java
  • 按照特定的字符拆分字段

    按照 , 或者特定的字符进行分割,把值取出来,举个例子,数据是:

    a,b,c
    d,e,f

    显示结果是:
    a

    b

    c

    d

    e

    f

    解决方法:

    拆分表:    

    if not object_id('Tab'is null
        drop table Tab
    Go
    Create table Tab([Col1] int,[COl2] nvarchar(5))
    Insert Tab
    select 1,N'a,b,c' union all
    select 2,N'd,e' union all
    select 3,N'f'
    Go
      
    --SQL2000用辅助表:
    if object_id('Tempdb..#Num'is not null
        drop table #Num
    go
    select top 100 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns b
    Select 
        a.Col1,COl2=substring(a.Col2,b.ID,charindex(',',a.Col2+',',b.ID)-b.ID) 
    from 
        Tab a,#Num b
    where
        charindex(',',','+a.Col2,b.ID)=b.ID --也可用 substring(','+a.COl2,b.ID,1)=','
    --2000不使用辅助表
    Select
        a.Col1,COl2=substring(a.Col2,b.number,charindex(',',a.Col2+',',b.number)-b.number) 
    from 
        Tab a join master..spt_values  b 
        ON B.type='p' AND B.number BETWEEN AND LEN(A.col2)
    where
         substring(','+a.COl2,b.number,1)=','
      
      
    SQL2005用Xml:
      
    select 
        a.COl1,b.Col2
    from 
        (select Col1,COl2=convert(xml,'<root><v>'+replace(COl2,',','</v><v>')+'</v></root>'from Tab)a
    outer apply
        (select Col2=C.v.value('.','nvarchar(100)'from a.COl2.nodes('/root/v')C(v))b
      
    SQL05用CTE:
      
    ;with roy as 
    (select Col1,COl2=cast(left(Col2,charindex(',',Col2+',')-1) as nvarchar(100)),Split=cast(stuff(COl2+',',1,charindex(',',Col2+','),''as nvarchar(100)) from Tab
    union all
    select Col1,COl2=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)),Split= cast(stuff(Split,1,charindex(',',Split),''as nvarchar(100)) from Roy where split>''
    )
    select COl1,COl2 from roy order by COl1 option (MAXRECURSION 0)
      
    生成结果:
    /*
    Col1        COl2
    ----------- -----
    1           a
    1           b
    1           c
    2           d
    2           e
    3           f
    */
    方法:
    if not object_id(N'Tempdb..#T'is null
        drop table #T
    Go
    Create table #T([Col1] nvarchar(9))
    Insert #T
    select N'苹果/橘子/梨' union all
    select N'香蕉/鸭蛋/巧克力' union all
    select N'饼干/果粒橙'
    Go
    Select 
    substring(a.[Col1],b.number,charindex('/',a.[Col1]+'/',b.number)-b.number)  
    from #T AS a,master.dbo.spt_values AS b
    WHERE b.type='P' AND CHARINDEX('/','/'+[Col1],b.number)=b.number
  • 相关阅读:
    HDU 1850 Being a Good Boy in Spring Festival
    UESTC 1080 空心矩阵
    HDU 2491 Priest John's Busiest Day
    UVALive 6181
    ZOJ 2674 Strange Limit
    UVA 12532 Interval Product
    UESTC 1237 质因子分解
    UESTC 1014 Shot
    xe5 android listbox的 TMetropolisUIListBoxItem
    xe5 android tts(Text To Speech)
  • 原文地址:https://www.cnblogs.com/zhycyq/p/2828041.html
Copyright © 2011-2022 走看看