当有很多信息时,这样的查询太慢了!所以在使用中,应当建立触发器,在插入“表B”的资料时剔出循环并将所用可能的“起止”点写入另外一个表中。你的这个例子只能作为一个教学上可行的题目使用。假设查询从 @f 到 @t 的车次,并且假设你的“表B”没有循环:declare @result(车次 int)
declare @step(车次 int,站次 int,车站 varchar(30))
insert @step(车次,站次,车站) select 车次,站次,车站 from 表B where 车站=@f
while (select count(*) from @step)>0
  begin
  insert @result(车次) select 车次 from @step where 车站=@t
  delete @step where 车站=@t
  update s set 站次=a.站次,车站=a.车站 
    from @step as s left join 表B as a on s.车次=a.车次 and s.站次+1=b.站次
  delete @step where 车站 is null
  end
select distinct 车次 from @result

解决方案 »

  1.   

    以上的是对楼主说的,不是对w_rose(w_rose)
      

  2.   

    select * from 表A x
    where exists (select 1 from 表B a,表B b
    where a.经由站='德阳'
    and b.经由站='江油'
    and a.车次ID=b.车次ID
    and a.站次<b.站次
    and a.车次ID=x.车次ID
    )
      

  3.   

    Rewiah给fyfok捐献了1000可用分;fyfok收到了:900可用分 没有分了发短消息给那些有红色星星的大虾要,来的久的久可能又可用分。
      

  4.   

    select * from 表A x
    where exists (select 1 from 表B a,表B b
    where a.经由站='德阳'
    and b.经由站='江油'
    and a.车次ID=b.车次ID
    and a.站次<>b.站次
    and a.车次ID=x.车次ID
    )
      

  5.   

    TO:Rewiah(乘长风)
    我不知道说社么好了,本来还麻烦大侠您,给果还让您倒贴分我一般在网上不用“您”,怕有代沟,可现在没办法了,真的谢谢了
      

  6.   

    select  distinct (select  distinct 车次ID from #t where  车次ID=a.车次ID and 站次<>a.站次) as 车次ID
    from  t a   where a.经由站 in ('德阳','江油')select c.* from 
    (select  distinct (select  distinct 车次ID from B where  车次ID=a.车次ID and 站次<>a.站次) as 车次ID from  B a   where a.经由站 in ('德阳','江油'))a join A c
    on c.车次ID=a.车次ID