简体   繁体   中英

How to do a parent/child database 'roll-up'?

How do you properly go about rolling up and selecting all users for each parent company until there are no more parent companies?

I am using SQL Server 2008 R2 and I need to check if there is a @ParentID then select all the users for that company, if there is a @ParentID on that company do the same thing, ad infinity?

Thanks. I am completely new to Rollups but am just trying something like the below to get the basic query idea started.

USE [DB]

DECLARE @UserName VARCHAR(250) = 'crusher@abc.com'
DECLARE @ParentID INT = -1

WHILE (@ParentID <> 0)
BEGIN
    SELECT @ParentID = CASE 
            WHEN ParentCompanyID IS NULL
                THEN 0
            ELSE ParentCompanyID
            END
    FROM User2Company a
    LEFT JOIN dbo.CompanyInfo b ON a.CompanyID = b.CompanyID
    LEFT JOIN dbo.widgets ON a.companyid = widgets.companyid
    WHERE a.UserName = @UserName

    PRINT @ParentID
END

    --SELECT * FROM CompanyInfo
    --WHERE CompanyID = 100274
    --SELECT *
    --FROM CompanyInfo
    --WHERE CompanyID = 100273

The commented code is just a hypothetical example of where the original query found a parent CompanyID of 100274... then THAT company found a parent CompanyID of 100273... until ultimately CompanyID 100273 had a ParentCompanyID of 0 in it's column.

HOw is this typically done?

DESIRED Output from the first query might look like this:

100274
100273
0

At which point I would fetch all user's from those company id's.

It's typically done with a recursive CTE:

;WITH
    tmp AS
    (
        SELECT  CompanyID,
                ParentCompanyID
        FROM    CompanyInfo
        WHERE   CompanyID = 100274
        UNION ALL
        SELECT      com.CompanyID,
                    com.ParentCompanyID
        FROM        CompanyInfo com
        INNER JOIN  tmp         tmp ON com.CompanyID = tmp.ParentCompanyID -- This is the recursive part
    )

SELECT * FROM tmp

And as others have said, avoid using loops in SQL Server. If you have to use loop, 99% of the time you are not using SQL Server properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM