|
发表于 2013-11-6 00:39:13
|
显示全部楼层
試試看 這個範例 看你可以理解嗎??
*****範例二 有深度 依照階層 展開..................計算用量
Create table [bom]([父件編碼] nvarchar(5),[子件編碼] nvarchar(7),[用量] int)
Insert bom
Select 'a','a.1',2 union all
Select 'a','a.2',1 union all
Select 'a','a.3',2 union all
Select 'a.1','a.1.1',3 union all
Select 'a.1','a.1.2',4 union all
Select 'a.1','a.1.3',2 union all
Select 'a.2','a.2.1',2 union all
Select 'a.2','a.2.2',2 union all
Select 'a.1.1','a.1.1.1',1 union all
Select 'a.1.1','a.1.1.2',2
Go
--創建函數1
If not object_id('f_getbom1') is null
Drop function f_getbom1
Go
create function f_getbom1(@No varchar(10))
returns @t table(父件編碼 varchar(10),子件編碼 varchar(10),用量 int,lvl int)
as
begin
declare @i int
set @i=1
insert @t select *,@i from bom where 父件編碼=@No
while @@rowcount>0
begin
set @i = @i + 1
insert @t
select a.父件編碼,a.子件編碼,a.用量*b.用量,@i
from bom a,@t b
where a.[父件編碼]=b.[子件編碼]
and b.lvl=@i-1
end
return
end
go
--創建函數2
If not object_id('f_getbom2') is null
Drop function f_getbom2
Go
create function f_getbom2(@No varchar(10),@lvl int)
returns table
as
return(
select 子件編碼 as 編碼,用量
from f_getbom1(@No) a
where lvl<=@lvl
and not exists(
select 1
from f_getbom1(@No)
where lvl<=@lvl
and a.子件編碼=父件編碼)
)
go
--調用查詢
select * from f_getbom2('a',1) |
评分
-
查看全部评分
|