求一问题解~,具体见下

Scarroot 2006-07-06 03:42:58
求一问题解~,具体见下:

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,
如果全部记录都存在,则返回错误

不知我有没有描述清楚?

(当然效率越高越好.)

谢谢咯~~

...全文
105 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
fcuandy 2006-07-06
  • 打赏
  • 举报
回复
嗯。用连接也是可以的。
Scarroot 2006-07-06
  • 打赏
  • 举报
回复
好像这个可以

select top 99 identity(int , 1 , 1 ) seq_no into #1 from syscolumns a
cross join syscolumns b

select 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 null



drop table #1
drop table #2
Scarroot 2006-07-06
  • 打赏
  • 举报
回复
fcuandy 2006-07-06
  • 打赏
  • 举报
回复
改进一下,增加两个变量,减少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
fcuandy 2006-07-06
  • 打赏
  • 举报
回复
--drop table #t
declare @a table
(style_id int)
insert @a
select 1 union all select 2 union all select 5

declare @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
end

select * from @a
drop table #t

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧