id(父级) cid(子级) select 1 from bom a where a.id in (select cid from bom where id=a.cid)
--对于楼主这个问题,可以参考一下下面的处理方法.--产品结构的循环冗余校验/*--环境 par是加工件,part是此加工件需要的零件 要求,给出par,part,检查是否会形成循环--思路 从给出的part出发,如果能找到一条par为给出的par的 证明会形成循环,否则不能. 针对下面的表来描述: 如果要新增 par='d' part='a' 从a出发,可以得到这样一条 d--b--a 如果再新增,就会形成循环 d--b--a--d --*/--创建测试表 create table 表(par varchar(10),part varchar(10)) insert into 表 select 'a','b' union all select 'a','c' union all select 'b','d' union all select 'b','e' union all select 'd','a' go--创建检查的函数 create function f_chk( @par varchar(10), --父零件 @part varchar(10) --子零件 ) returns bit as begin declare @t table(par varchar(10),i int) declare @i int,@re bit
select @re=1,@i=0 if exists(select * from 表 where part=@part and par=@par) goto lb_re insert into @t select par,@i from 表 where part=@part while @@rowcount>0 begin if exists(select 1 from 表 a join @t b on a.part=b.par where b.i=@i and a.par=@par) goto lb_re set @i=@i+1 insert into @t select a.par,@i from 表 a join @t b on a.part=b.par where b.i=@i-1 end set @re=0lb_re: return(@re) end go--调用示例 select dbo.f_chk('d','a')go --删除测试 drop table 表 drop function f_chk
select 1 from bom a where a.id in (select cid from bom where id=a.cid)
par是加工件,part是此加工件需要的零件
要求,给出par,part,检查是否会形成循环--思路
从给出的part出发,如果能找到一条par为给出的par的
证明会形成循环,否则不能.
针对下面的表来描述:
如果要新增
par='d' part='a'
从a出发,可以得到这样一条
d--b--a
如果再新增,就会形成循环
d--b--a--d
--*/--创建测试表
create table 表(par varchar(10),part varchar(10))
insert into 表
select 'a','b'
union all select 'a','c'
union all select 'b','d'
union all select 'b','e'
union all select 'd','a'
go--创建检查的函数
create function f_chk(
@par varchar(10), --父零件
@part varchar(10) --子零件
) returns bit
as
begin
declare @t table(par varchar(10),i int)
declare @i int,@re bit
select @re=1,@i=0
if exists(select * from 表 where part=@part and par=@par)
goto lb_re insert into @t select par,@i from 表 where part=@part
while @@rowcount>0
begin
if exists(select 1 from 表 a join @t b on a.part=b.par where b.i=@i and a.par=@par)
goto lb_re
set @i=@i+1
insert into @t select a.par,@i from 表 a join @t b on a.part=b.par
where b.i=@i-1
end
set @re=0lb_re:
return(@re)
end
go--调用示例
select dbo.f_chk('d','a')go
--删除测试
drop table 表
drop function f_chk