日期:2014-05-17 浏览次数:20456 次
--那你试下这个,bom表太大的话,会比较慢,可以分2次展bom
declare @t1 table(id varchar(10),pid varchar(10))
insert into @t1 values('01','0')
insert into @t1 values('02','0')
insert into @t1 values('03','0')
insert into @t1 values('0101','01')
insert into @t1 values('0102','01')
insert into @t1 values('0201','02')
insert into @t1 values('0301','03')
insert into @t1 values('0302','03')
insert into @t1 values('010101','0101')
insert into @t1 values('020101','0201')
insert into @t1 values('01010101','010101')
insert into @t1 values('030201','0302')
insert into @t1 values('030202','0302')
declare @t2 table(id int, did varchar(10))
insert into @t2 values(1,'01010101')
insert into @t2 values(2,'03')
insert into @t2 values(3,'0201')
declare @id varchar(10)
set @id='0302'
;with cte_bom
as
(
select id,pid ,
rights= case when exists(select 1 from @t2 where did=A.pid )
then 1 else 0 end,
flag = case when pid=@id or id=@id then 1 else 0 end
from @t1 as A where not exists(select 1 from @t1 where id=A.pid)
union all
select A.id,A.pid,
case when cte_bom.rights =1 then 1 else
case when exists(select 1 from @t2 where did=A.pid )
then 1 else 0 end
end,
flag = case when flag=1 then 1 else
case when A.id=@id then 1 else 0 end
end
from cte_bom,@t1 as A
where cte_bom.id = A.pid
)
select id,pid
from cte_bom as A
where not exists(select 1 from @t1 where pid=A.id)
and (rights=1 or exists(select 1 from @t2 where did=A.id )