数据库的结构是   
id       patentID 
1             0 
2             1 
3             2 
4             3 
5             4 
6             5 
7             6 
8             0 
9             8 
10           0 
11           8 
12           9 
…… 
当只知道id为某一值或某几值时,怎么能够查出给出id的所有父级和他们的子级 
如:id=(3,4)时 
怎么写能查出 
id       patentID 
1             0 
2             1 
3             2 
4             3 
5             4 
6             5 
7             6 

解决方案 »

  1.   

    create table test_dg(id integer ,parent_id integer)
    insert test_dg(id,parent_id) select
    1,                           0 union all select
    2,                           1 union all select
    3,                           2 union all select
    4,                           3 union all select
    5,                           4 union all select
    6,                           5 union all select
    7,                           6select * from test_dgcreate procedure usp_getchildandparent(@c_id int,@p_id int)
    AS
    begin
    declare @t_id integer
    declare @tc_id integer
    declare @tp_id integer
    create table #t(id int,parent_id int)
       if @c_id<@p_id 
       BEGIN
            set @t_id=@c_id
            set @c_id=@p_id
            set @p_id=@t_id
       END
        set @tc_id=@c_id
        set @tp_id=@p_id
        
        set @tc_id=@tc_id-1
        set @tp_id=@tp_id-1
       while exists(select * from test_dg where id=@tc_id and parent_id=@tp_id)
             BEGIN
                  insert into #t(id,parent_id) select id,parent_id from test_dg where id=@tc_id and parent_id=@tp_id
                  set @tc_id=@tc_id-1
                  set @tp_id=@tp_id-1
             end
             
        set @tc_id=@c_id
        set @tp_id=@p_id
             
        set @tc_id=@tc_id+1
        set @tp_id=@tp_id+1
       while exists(select * from test_dg where id=@tc_id and parent_id=@tp_id)
             BEGIN
                  insert into #t(id,parent_id) select id,parent_id from test_dg where id=@tc_id and parent_id=@tp_id
                  set @tc_id=@tc_id+1
                  set @tp_id=@tp_id+1
             end
             
       select * from #t order by id
       
       drop table #t  
    endexec usp_getchildandparent 4,3