问题如下:
tableA                                   tableB
A_id  parent_id   A_name                 B_id   A_id       A
|
----A1
|  |
|  |------A11
|       |-----a111
----A2
    |---a21形成这么一种树形结构。
其中A   A1   A2   A11在tableA中,  a111   a21在tableB中。
现在想通过一个语句找出所有属于A*的a*.
比如 A 下面有   a111 和 a21
     A1下面有   a111
     A2下面有   a21怎么写啊这个sql语句???

解决方案 »

  1.   

    --try
    create function f_cid(@id varchar(10))
    returns @t table(id varchar(10),level int)
    AS
    begin
    declare @level int
    set @level=1
    insert into @t select @id,@level
    while @@rowcount>0
    begin
      set @level=@level+1
      insert into @t select a.[A_id],@level
      from TableA  a,@t b
      where a.[parent_id]=b.[id]
      and b.level=@level-1
    end
    return
    endGOselect t2.B_id  from dbo.f_cid('A') t1,tableB t2
    where t1.id=t2.A_id