SQL is implemented recursively (find the child according to the parent node)

1, 2005 before the database, use the function to achieve. (Find parent node according to child nodes)

object_id IF ( 'f_getParentBySon') IS Not null drop function f_getParentBySon
the GO
the CREATE function f_getParentBySon (@id VARCHAR (100))
the RETURNS @t Table (ID VARCHAR (100))
AS
the begin
INSERT INTO @t @id SELECT
SELECT @ ID = Parid from BOM_Detail where id = @id and Parid is not null - the first performance, the data input id = id where all find out, and then the parent id assigned to the variable (when the purpose is the same sub-id involved in more than one parent find out all the parent product) when constructing the goods
the while @@ ROWCOUNT> 0
the begin
INSERT INTO @t the SELECT @id the SELECT @id = Parid from the above mentioned id = BOM_Detail the WHERE iS @id and Parid not null - check out the merchandise has been father the new data assignment variables, and once again the father of a new product to the variable data query, data query out of the loop until no
End
return
End
Go

使用:select  a.*  from BOM_Detail a , f_getParentBySon('000020000600005') b where a.id= b.id 

2, 2005 after the database, with as aid statement (based on purpose is still to find a child node parent node)

 ;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 - query data

For examples with as demo, with the help of God's great article https://www.cnblogs.com/hshuai/p/3947424.html

 

Guess you like

Origin www.cnblogs.com/zhh-blogs/p/11648804.html