Select products where the category belongs to any category in the hierarchy

前端 未结 9 1642
再見小時候
再見小時候 2021-02-06 05:39

I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:

Compu         


        
9条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 06:11

    This should recurse down all the 'child' catagories starting from a given catagory.

    DECLARE @startingCatagoryId int
    DECLARE @current int
    SET @startingCatagoryId = 13813 -- or whatever the CatagoryId is for 'Processors'
    
    CREATE TABLE #CatagoriesToFindChildrenFor
    (CatagoryId int)
    
    CREATE TABLE #CatagoryTree
    (CatagoryId int)
    
    INSERT INTO #CatagoriesToFindChildrenFor VALUES (@startingCatagoryId)
    
    WHILE (SELECT count(*) FROM #CatagoriesToFindChildrenFor) > 0
    BEGIN
        SET @current = (SELECT TOP 1 * FROM #CatagoriesToFindChildrenFor)
    
        INSERT INTO #CatagoriesToFindChildrenFor
        SELECT ID FROM Catagory WHERE ParentCatagoryId = @current AND Deleted = 0
    
        INSERT INTO #CatagoryTree VALUES (@current)
        DELETE #CatagoriesToFindChildrenFor WHERE CatagoryId = @current
    END
    
    SELECT * FROM #CatagoryTree ORDER BY CatagoryId
    
    DROP TABLE #CatagoriesToFindChildrenFor
    DROP TABLE #CatagoryTree
    

提交回复
热议问题