1,數據庫2005之前,使用函數實現。(根據子節點查找父節點)
if object_id('f_getParentBySon') is not null drop function f_getParentBySon
GO
CREATE function f_getParentBySon(@id varchar(100))
RETURNS @t table(id varchar(100))
as
begin
insert into @t select @id
select @id= Parid from BOM_Detail where id= @id and Parid is not null --第一次執行,將id=輸入的id 所在數據全部查出,然后將父id賦給變量(目的是當同一個子id參與了多個父商品的構造時查出所有的父商品)
while @@ROWCOUNT > 0
begin
insert into @t select @id select @id = Parid from BOM_Detail where id= @id and Parid is not null --查詢出已經被父商品賦值的變量的新數據,並再次將新數據的父產品賦給變量進行查詢,直至無數據查詢跳出循環
end
return
end
go
使用:select a.* from BOM_Detail a , f_getParentBySon('000020000600005') b where a.id= b.id
2,數據庫2005之后,借助 with as 語句(目的仍然是根據子節點查找父節點)
;WITH subqry AS
(
SELECT tb.id, tb.qty, tb.parid FROM tb WHERE id=@id
UNION ALL
SELECT tb.id, tb.qty, tb.parid FROM tb,subqry
WHERE tb.id= subqry.Parid
)
select * from subqry --查詢數據
關於with as demo的實例,借助大神的一篇文章https://www.cnblogs.com/hshuai/p/3947424.html