现在我有一4个表   
表1的表名为:A_P
ID 代号 归类
1 A001 P
2 A002 M
3 A003 P
4 A004 M表2的表名为表1中的归类字段为‘M’的代号记录:A002   
ID 代号 归类
1 BX001 P
2 CX001 M表3的表名为表1中的归类字段为‘M’的代号记录:A004
ID 代号 归类
1 CX002 P
2 CX005 P表4的表名为表1中的归类字段为‘M’的代号记录:CX001
ID 代号 归类
1 DX001 P
2 DX005 P我现在需要做的是:
从A_P表开始查,查出归类为P或M的记录,并且遇到归类为M的记录就继续查其所对应的代号为表名的表,并将此表中查出的内容添加级别代号,比如:“.1”,依次类推,“..1”……(这中间需要插入临时表保存查出来的记录,并且查出来的下级内容紧贴放置在父级记录的下面)
如何实现呢?
(四个表只是一个说明,其实有成千上万个表)

解决方案 »

  1.   

    静态BOM物料表可以更方面单独维护,这就是表结构这样设计的好处
      

  2.   

    动态递归,还木有加上点...
    create table A_P(ID int,代号 varchar(10),归类 varchar(10))
    insert into A_P select 1,'A001','P'
    insert into A_P select 2,'A002','M'
    insert into A_P select 3,'A003','P'
    insert into A_P select 4,'A004','M'
    create table A002(ID int,代号 varchar(10),归类 varchar(10))
    insert into A002 select 1,'BX001','P'
    insert into A002 select 2,'CX001','M'
    create table A004(ID int,代号 varchar(10),归类 varchar(10))
    insert into A004 select 1,'CX002','P'
    insert into A004 select 2,'CX005','P'
    create table CX001(ID int,代号 varchar(10),归类 varchar(10))
    insert into CX001 select 1,'DX001','P'
    insert into CX001 select 2,'DX005','P'
    go
    declare @sql nvarchar(max)
    create table #1(代号 varchar(20))
    select @sql=isnull(@sql+' union all ','')+'select 代号 from '+a.name +' where 归类=''M'''
    from sys.objects a inner join sys.columns b on a.object_id=b.object_id
    where type='U' and 
    exists (select 1 from sys.columns where object_id=b.object_id and name='代号' ) and
    exists (select 1 from sys.columns where object_id=b.object_id and name='归类' )
    set @sql='select distinct * from('+@sql+')t'
    insert into #1 exec(@sql)
    set @sql=null
    select @sql=isnull(@sql+' union all ','')+'select * from '+代号 from #1
    set @sql='select * from A_P union all '+@sql
    exec(@sql)
    /*
    ID          代号         归类
    ----------- ---------- ----------
    1           A001       P
    2           A002       M
    3           A003       P
    4           A004       M
    1           BX001      P
    2           CX001      M
    1           CX002      P
    2           CX005      P
    1           DX001      P
    2           DX005      P(10 行受影响)*/
    go
    drop table A_P,A002,A004,CX001,#1