TSQL递归查询更新临时表

时间:2014-10-14 18:18:03

标签: sql sql-server tsql stored-procedures recursion

我有一个递归遍历我的员工ORG的查询,并获得向VP报告的所有人的列表。此查询按预期工作:

DECLARE @pit AS DATETIME = GETDATE();

DECLARE @table TABLE (
    mgrQID     VARCHAR (64) ,
    QID        VARCHAR (64) ,
    NTID       VARCHAR (64) ,
    FullName   VARCHAR (256),
    lvl        INT          ,
    metadate   DATETIME     ,
    totalCount INT          );

WITH   empList (mgrQID, QID, NTID, FullName, lvl, metadate)
AS     (SELECT   TOP 1 mgrQID,
                       QID,
                       NTID,
                       FirstName + ' ' + LastName,
                       0,
                       Meta_LogDate
        FROM     dbo.EmployeeTable_Historical
        WHERE    QID IN (SELECT director
                         FROM   dbo.attritionDirectors)
                 AND Meta_LogDate <= @pit
        ORDER BY Meta_LogDate DESC
        UNION ALL
        SELECT   b.mgrQID,
                 b.QID,
                 b.NTID,
                 b.FirstName + ' ' + b.LastName,
                 lvl + 1,
                 b.Meta_LogDate
        FROM     empList AS a CROSS APPLY dbo.Fetch_DirectsHistorical_by_qid (a.QID, @pit) AS b)
-- Insert into the counts table
INSERT INTO @table (mgrQID, QID, NTID, FullName, lvl, metadate, totalCount)
SELECT   empList.mgrQID,
         empList.QID,
         empList.NTID,
         empList.FullName,
         empList.lvl,
         empList.metadate,
         '0'
FROM     empList
ORDER BY lvl
OPTION (MAXRECURSION 10);

如您所见,我有一个名为totalCount的表列,我在第一个递归查询中将其设置为0

我现在有第二个查询,该查询遍历该临时表中的所有人,并找到直接报告的总数。

例如,如果一名董事有3位经理,每位经理有3名员工,则会有12人报告董事; 9名员工和3名经理。

这来自以下查询:

;WITH     a
AS       (SELECT mgrQID AS direct,
                 QID
          FROM   @table AS t
          WHERE  QID IN (SELECT QID
                         FROM   @table)
          UNION ALL
          SELECT a.direct,
                 t.QID
          FROM   @table AS t
                 INNER JOIN
                 a
                 ON t.mgrQID = a.QID)
--subtracting 1 because it is also counting the manager
SELECT   direct,
         count(*) - 1 AS totalCount
FROM     a
GROUP BY direct
OPTION (MAXRECURSION 10);

我的问题是......

如何使用第二个查询中的计数更新@temp totalCount? QID和Direct是两者中共同的两个领域。

1 个答案:

答案 0 :(得分:0)

试试这个:

update t
set t.totalCount = a.count(*) - 1
from a
join @temp t
    on a.Direct = t.QID
group by a.direct, t.QID
option (maxrecursion 10)