Insert products Select 1, 'A1 ', '1 '
Union All Select 2, 'A2 ', '2 '
Union All Select 3, 'A3 ', '3 '
Union All Select 5, 'A5 ', '3 '
Union All Select 6, 'B1 ', '5 '
Union All Select 7, 'B2 ', '6 '
Insert ProductType Select 1, 'A ', 0, 1, 1
Union All Select 2, 'A1 ', 1, 2, 1
Union All Select 3, 'A2 ', 2, 3, 1
Union All Select 5, 'B ', 0, 1, 2
Union All Select 6, 'B1 ', 5, 2, 2
Create Function F_GetChildren(@Typeproductname nvarchar(50))
Returns @Tree Table (ProductTypeID Int)
As
Begin
Insert @Tree Select ProductTypeID From ProductType Where Typeproductname = @Typeproductname
While @@Rowcount > 0
Insert @Tree Select A.ProductTypeID From ProductType A Inner Join @Tree B On A.ParentID = B.ProductTypeID And A.ProductTypeID Not In (Select ProductTypeID From @Tree)
Return
End
Select * From products Where ProductTypeID In (Select ProductTypeID From dbo.F_GetChildren( 'A '))