SQL

大概意思是:
创建一个表tt,
字段分别为a,b
然后插入值
'a01' , '1,2,3,4,5,6'
'a02' , '1,2,3'
'a03' , '4,5,6' 
将变量@b赋值
然后根据变量b得到结果
a                   b
--------------------------------
 a01               1,2,3,4,5,6
 a03               4,5,6最后删除表tt大概就是这样,但没有条件,语句是错的!

解决方案 »

  1.   

    create table tt (a varchar(20),b varchar(20))
    insert into tt (a,b)
    select 'a01','1,2,3,4,5,6'
    union all 
    select 'a02','1,2,3'
    union all
    select 'a03','4,5,6' declare @b nvarchar(1000)
    set @b='1,4,5'declare @s nvarchar(4000)
    set @s='select '
    select @s=@s+''''+a+replace(b,',',''' union all select '''+a)+''' union all select ' from tt
    set @s=left(@s,len(@s)-17)
    set @b='create table ##b(col2 int) insert into ##b select '+replace(@b,',',' union all select ')
    print @b
    set @s='create table ##t(col1 nvarchar(10)) insert into ##t '+@s+' '+@b
            +' select * into ##a from (select * from ##t left join ##b on right(##t.col1,1)=##b.col2)t'
            +' select * from tt where a in(select left(col1,3) from ##a where col2 is not null group by left(col1,3) having count(*)>1)'
            +' drop table ##t drop table ##b drop table ##a'
    print @s
    exec(@s)drop table tt
      

  2.   

    当@b='1,2,3'
    --result
    a                   b
    --------------------------------
     a01               1,2,3,4,5,6
     a02               1,2,3create table tt (a varchar(20),b varchar(20))
    insert into tt (a,b)
    select 'a01','1,2,3,4,5,6'
    union all 
    select 'a02','1,2,3'
    union all
    select 'a03','4,5,6' declare @b nvarchar(1000)
    set @b='1,2,5'declare @s nvarchar(4000)
    set @s='select '
    select @s=@s+''''+a+replace(b,',',''' union all select '''+a)+''' union all select ' from tt
    set @s=left(@s,len(@s)-17)
    set @b='create table ##b(col2 int) insert into ##b select '+replace(@b,',',' union all select ')
    print @b
    set @s='create table ##t(col1 nvarchar(10)) insert into ##t '+@s+' '+@b
            +' select * into ##a from (select * from ##t left join ##b on right(##t.col1,1)=##b.col2)t'
            +' select * from tt where a in(select left(col1,3) from ##a where col2 is not null group by left(col1,3) having count(*)>1)'
            +' drop table ##t drop table ##b drop table ##a'
    print @s
    exec(@s)drop table tt