主表的内容为
材料名称
AA
C
子表的内容为
父材料名称 材料名称 数量
AA   a   0
AA   b   2
AA   C   3
C   R   2
C   W   2查询AA所包括的子材料结果应该如下
数量 子表.材料名称
0 a
2 b
6 W
6 R这个查询该如何写呢,谢谢

解决方案 »

  1.   

    參照
    http://blog.csdn.net/roy_88/archive/2006/12/24/1458449.aspx
      

  2.   

    create function roy_f(@项目 varchar(20))
    returns varchar(100)
    as
    begindeclare @上级项目 varchar(20)select @上级项目=上级项目 from ta where 项目=@项目return case when @上级项目 is null then null             else  isnull(dbo.roy_f(@上级项目)+'-','')+@项目 end
    end 这个函数里的return,也是无条件退出吗
      

  3.   

    去邹建的BLOG有这方面详细的资料
    http://blog.csdn.net/zjcxc/archive/2007/08/29/1763598.aspx
      

  4.   


    if not object_id('Tempdb..#T2') is null
    drop table #T2
    Go
    Create table #T2([父材料名称] nvarchar(2),[材料名称] nvarchar(2),[数量] int)
    Insert #T2
    select N'AA',N'a',0 union all
    select N'AA',N'b',2 union all
    select N'AA',N'C',3 union all
    select N'C',N'R',2 union all
    select N'C',N'W',2
    Go;with C
    as
    (select * from #T2 where [父材料名称]='AA' --查AA
    union all
    select a.[父材料名称],a.[材料名称],[数量]=c.[数量]*a.[数量] from #T2 a join C  on a.[父材料名称]=c.[材料名称])
    select
    [材料名称],sum([数量])[数量]
    from 
    C a
    where
    not exists(select * from C where a.[材料名称]=c.[父材料名称])
    group by [材料名称]
    材料名称 数量
    ---- -----------
    a    0
    b    2
    R    6
    W    6(4 個資料列受到影響)
      

  5.   

    这里面的;with C
    是什么意思呢,我不太明白,能不能再解释一下,非常感谢
      

  6.   

    我还是不能明白 with c 的意思,能不能详细解释一下,非常感谢
      

  7.   

    公用表表达式,
    是SQL 2005里面新增加的功能,
    对于处理这种BOM等循环递归非常有效,
    使用公用表表达式
    http://technet.microsoft.com/zh-cn/library/ms190766.aspx
    使用公用表表达式的递归查询
    http://technet.microsoft.com/zh-cn/library/ms186243.aspx
      

  8.   


    if object_id('A')is not null
       drop table A
    if object_id('B')is not null
       drop table B
    if object_id('Tem') is not null
       drop table Tem
    if object_id('D') is not null
       drop table D
    go
    create table A
    ( 材料名称 nvarchar(2)
    )
    insert into A select 'AA'
        union all select 'C'
    create table B
    ( 父材料名称 nvarchar(2),
      材料名称  nvarchar(2),
      数量 int
    )
    insert into B select 'AA','a',0
        union all select 'AA','b',2
        union all select 'AA','C',3
        union all select 'C','R',2
        union all select 'C','W',2
    go
    select 数量,材料名称 into tem from B where 材料名称='C'
    select 数量= tem.数量*B.数量,B. 材料名称 into D  from B inner join tem 
    on Tem.材料名称 = B.父材料名称
     
    select 数量,材料名称 from B where 父材料名称='AA' and 材料名称<>'C'
    union all 
    select * from D