name
ASIA,EUROPE
ASIA,EUROPE,INDIA
ASIA,EUROPE,INDIA,LATIN,S.PAC,DOMESTIC
ASIA,EUROPE,S.PAC
ASIA,INDIA,S.PAC
DOMESTIC
EUROPE
EUROPE,INDIA
EUROPE,S.PAC
INDIA
LATIN
MEMO
S.PAC
动态产生的一个结果集,想仅仅要这样的数据
ASIA
EUROPE
INDIA
LATIN
S.PAC
DOMESTIC
MEMO就是把产生的记录不重复,如写这个sql

解决方案 »

  1.   

    对字符串拆分并求并集:declare @tb table (id int,col varchar(50))
    insert @tb 
    select 1,'1,2,3,4' union all
    select 1,'1,3,4' union all
    select 1,'1,4' union all
    select 2,'11,3,4' union all
    select 2,'1,33,4' union all
    select 3,'1,3,4'-----------------------------------------------
    --字符串并集
    declare @tb2 table (id int,col varchar(50))
    declare @t table (id int identity(1,1),b bit )insert into @t(b)
    select top 50 1
    from sysobjects a,sysobjects binsert into @tb2
    select tb.id,substring(tb.col,a.id,charindex(',',tb.col+',',a.id)-a.id)
    from @tb tb ,@t a
    where a.id<=len(tb.col)
          and charindex(',',','+tb.col,a.id)=a.id
    group by tb.id ,substring(tb.col,a.id,charindex(',',tb.col+',',a.id)-a.id)--select * from @tb2declare @col1 varchar(50),@col2 varchar(50)
    update @tb2
    set @col2=case when @col1=id then @col2+','+col else col end,
    @col1=id,
    col=@col2select id,max(col) from @tb2 b
    group by id
      

  2.   

    To:HEROWANGn复杂啊,不能简单点吗?
      

  3.   

    --> --> (Andy)生成测试数据 2008-12-11
    Set Nocount On
    if not object_id('test') is null
    drop table test
    Go
    Create table test([name] nvarchar(500))
    Insert test
    select N'ASIA,EUROPE' union all
    select N'ASIA,EUROPE,INDIA' union all
    select N'ASIA,EUROPE,INDIA,LATIN,S.PAC,DOMESTIC' union all
    select N'ASIA,EUROPE,S.PAC' union all
    select N'ASIA,INDIA,S.PAC' union all
    select N'DOMESTIC' union all
    select N'EUROPE' union all
    select N'EUROPE,INDIA' union all
    select N'EUROPE,S.PAC' union all
    select N'INDIA' union all
    select N'LATIN' union all
    select N'MEMO' union all
    select N'S.PAC'
    Go
    If Object_id('tempdb..#') Is Not Null
    Drop Table #
    If Object_id('tempdb..#Return') Is Not Null
    Drop Table #ReturnDeclare @rows int,@name nvarchar(500)
    Select name Into #Return From test Where Patindex('%,%',name)=0 
    Select id=Identity(int,1,1),name Into # From test Where Patindex('%,%',name)>0
    Set @rows=@@ROWCOUNT
    While @rows>0
    Begin
    Select @name=[name]+',' From # Where id=@rows
    While @name>''
    Begin
    Insert Into #Return Select Left(@name,Charindex(',',@name)-1)
    Set @name=Stuff(@name,1,Charindex(',',@name),'')
    End
    Set @rows=@rows-1
    End
    Select Distinct name From #Return