补充说明:
计算方法只涉及表一
不使用表二。

解决方案 »

  1.   

    --你把表结构贴出来.
    --至少要遍历你表的某一节点
      

  2.   

    --生成测试数据
    create table BOM(产品编码 INT,子产品编码 INT)
    insert into BOM select 1,2
    insert into BOM select 2,3
    insert into BOM select 3,4
    insert into BOM select 5,4
    insert into BOM select 6,4
    --创建用户定义函数
    create function f_getlevel(@Product_ID INT)
    returns  @t table(Product_ID INT,Level INT)
    as
    begin
        declare @i int
        set @i = 0
        insert into @t select @Product_ID,@i
        
        while @@rowcount<>0
        begin
            set @i = @i + 1
            insert into @t select a.产品编码,@i from BOM a,@t b where a.子产品编码=b.Product_ID
            delete a from @t a where a.level = (@i-1) and  exists(select 1 from BOM where 子产品编码=a.Product_ID)
        end
        
        return
    end
    --执行查询
    select * from dbo.f_getlevel(4)
    --输出结果
    Product_ID   Level
    ----------   ------
    1            3
    5            1
    6            1