34,590
社区成员
发帖
与我相关
我的任务
分享
create table t
(parent varchar(10),
child varchar(10),qty numeric(9,2)
)
insert into t
select 'FG001', 'SFG001', 1 union all
select 'FG001' , 'SFG002', 1 union all
select 'FG001' ,'SFG003', 1 union all
select 'SFG001', 'WIP001', 2 union all
select 'SFG001' ,'WIP002', 2 union all
select 'SFG002' ,'WIP003', 3 union all
select 'SFG002' ,'WIP004', 3 union all
select 'SFG002' ,'WIP005', 2 union all
select 'SFG003' ,'WIP006', 3 union all
select 'WIP001' ,'RAW001', 2.66 union all
select 'WIP001' ,'RAW002' , 2.33 union all
select 'WIP002' ,'RAW003' , 3.21 union all
select 'WIP003' ,'RAW004' , 1.89 union all
select 'WIP003' ,'RAW005' , 1.86 union all
select 'RAW001','KKK001', 3.25 union all
select 'RAW004','KKK003', 4.26 union all
select 'KKK001','WWW005', 5.23
二:创建函数(a:树型结构显示)
create function test(@parent VARCHAR(10))
returns @t table(parent Nvarchar(10),child Nvarchar(10),qty numeric(9,2),
level int,sort Nvarchar(1000)collate Latin1_General_BIN )
as
begin
declare @level int
set @level=1
insert into @t
select parent,child,qty,@level,parent+child
from t
where parent=@parent collate Latin1_General_BIN
while @@rowcount>0
begin
set @level=@level+1
insert @t
select a.parent,a.child,a.qty*b.qty,@level,b.sort+a.child
from t a ,@t b
where a.parent=b.child collate Latin1_General_BIN
and b.level=@level-1
end
return
end
--调用函数
select
level,
space(level*2)+'|--' + child as 'product',
qty
from
dbo.test('FG001')
order by
sort
--结果
/**//*
level product qty
1 |--SFG001 1.00
2 |--WIP001 2.00
3 |--RAW001 5.32
4 |--KKK001 17.29
5 |--WWW005 90.43
3 |--RAW002 4.66
2 |--WIP002 2.00
3 |--RAW003 6.42
1 |--SFG002 1.00
2 |--WIP003 3.00
3 |--RAW004 5.67
4 |--KKK003 24.15
3 |--RAW005 5.58
2 |--WIP004 3.00
2 |--WIP005 2.00
1 |--SFG003 1.00
2 |--WIP006 3.00
(17 row(s) affected)
*/