产品ID   零件ID   
 001      002
 002      003
 003      004
 004      005如何由004查找到产品001的信息?急求该算法!

解决方案 »

  1.   


    declare @s nvarchar(50)
    declare @result nvarchar(50)
    set @s='004'
    while (exists(select 1 from 表 where [零件ID] = @s))
    begin
    select @result = [产品ID] from 表 where [零件ID] = @s
    set @s=@result
    end
    select @result
      

  2.   

    create table #temp(productid varchar(20),partsid varchar(20))
    insert into #temp
    select '001','002' union all
    select '002','003' union all
    select '003','004' union all
    select '004','005' union all
    select '005','006'declare @productid varchar(20)
    set @productid='004'
    ;with cte as(
    select productid,partsid from #temp where productid=@productid union all
    select t.* from cte c inner join #temp t on t.partsid=c.productid 
    )
    select top 1 * from cte order by productid
    /*
    001 002
    */
      

  3.   

    cte小数据量还不怎么明显,大数据量的递归确实效率没有循环的好。
      

  4.   

    需要嵌入在winform开发的代码中
      

  5.   

    C# 写法
    Class Product{
    String ProductID{get;set;}
    String PartID{get;set;}
    Public Product GetPart()
      {
        //根据PartID查询出 新的Product 并返回,如果没有的话返回空
      }
    }
    用法  Product.GetPart().GetPart()....
    遍历 直至PartID为空 就可以把所有的 信息查出来.