id pid(父类) name duck(深度)数据库如上设计,每次添加一条记录,如何让他的父类,以及祖先类加一或者减一?
我用的是sql2005

解决方案 »

  1.   

    如果父类 于子类的关系是1:n的话,还好办一点,可以用触发器,但深度太大了的话,也是会比较慢的如果父类 于子类的关系是n:n的话,那就使用存储过程了,而且是做最大深度个循环,这样再每插入一条的时候,更新父、祖类是不大实际的
      

  2.   

    create table t_tree(ID int, ParentID int)
    insert t_tree
    select 1,   -1 union all
    select 2,   1 union all
    select 3,   1 union all
    select 4,   2 union all
    select 5,   2 union all
    select 6,   3
    如下:create function roy_b(@r int)
    RETURNS @ta table(id int,parentid int)
    as
    begin
    While Exists(Select 1 From t_tree Where id=@r and parentid<>0)
    begin
    insert @ta select * from t_tree where id=@r
    select @r=parentid from t_tree where id=@r
    end
    RETURN 
    endselect * from dbo.roy_b(5)
    效果如下:
    id          parentid    
    ----------- ----------- 
    5           2
    2           1
    1           -1(所影响的行数为 3 行)
      

  3.   

    以上语句用于统计类别关连,楼主设计用一个简单trigger就可以完成了