求一问题解~,具体见下:table a
(style_id int)table b
(seq int,start_seq int,end_seq int)style_id 中为款号id,存在不连续的记录,如1,10,60,55,41,33... 最大不超过100
table b 为以下形式的记录
depart     start_seq    end_seq
1       2            16      一组
2       20           30      二组
3       62           90      三组
表示一组拥有 2~16 的号码(seq)
表示二组拥有 20~30 的号码(seq)
...现在要对根据a,b 生成新的一个 style_id
规则是:查找 b 中一组.2~16 的号码(seq)在 a 中有没有用过(出现过),递增查,即,首先查找2
在a 中有没有出现,如果有,则查3,....一直到16,如果都存在,则拿 b中的第二组 20~30 继续,
如果查到不存在,则把那个数字作为新的style_id,
如果全部记录都存在,则返回错误不知我有没有描述清楚?(当然效率越高越好.)谢谢咯~~

解决方案 »

  1.   

    --drop table #t
    declare @a table
    (style_id int)
    insert @a
    select 1 union all select 2 union all select 5declare @b table
    (seq int,start_seq int,end_seq int)
    insert @b select
    1  ,     2       ,     16
    union all select
    2 ,      20       ,    30
    union all select
    3,       62        ,   90
    select top 100 identity(int) id into #t from sysobjects,syscolumns
    --假设你的seq是连续的,如果不连续,那么借助count或临时表获得一个连续的列,这里不写那样的了,思路一样。
    declare @i int,@n int
    select @i=max(seq) from @b
    set @n=1
    while @n<=@i
    begin
    insert @a select id from #t where id>=(select start_seq from @b where seq=@n) and id<=(select end_seq from @b where seq=@n)  and id not in(select style_id from @a)
    set @n=@n+1
    endselect * from @a
    drop table #t
      

  2.   

    改进一下,增加两个变量,减少N次查询.
    declare @i int,@n int,@start_seq int,@end_seq int
    select @i=max(seq) from @b
    set @n=1
    while @n<=@i
    begin
    select @start_seq=start_seq,@end_seq=end_seq from @b where seq=@n
    insert @a select id from #t where id>=@start_seq and id<=@end_seq  and id not in(select style_id from @a)
    set @n=@n+1
    end
      

  3.   

    好像这个可以select top 99 identity(int , 1 , 1 ) seq_no into #1 from syscolumns a
    cross join  syscolumns bselect distinct a.* into #2 from #1  a
    inner join  b
    on (a.seq_no >=start_seq and a.seq_no <= end_seq)select min(m.seq_no)
    from #2 m
    left join a n
    on n.style_id = m.seq_no
    where n.style_id is nulldrop table #1
    drop table #2