0

作为一个从未从任何人那里得到过 SQL 指导/指示的人,我想听听你们应该如何进行以下查询。据我所知,像这样的循环是一种非常糟糕的做事方式。

我正在从这个查询中创建一个表:

DECLARE @maxReleases int
SET @maxReleases = 100000

DECLARE @RootReleases table (ReleaseId int, RootReleaseId int)

DECLARE @ctr int
Set @ctr = 1

WHILE(@ctr <= @maxReleases)
BEGIN
WITH cte_Releases
( 
  ReleaseId,
  Name, 
  ParentReleaseID

) 
AS( 
  SELECT  
   ReleaseId, 
   Name,
   ParentReleaseID

  FROM Releases
  Where ReleaseId = @ctr

 UNION ALL 

 SELECT  
  R.ReleaseId,
  R.Name,
  R.ParentReleaseID 
 FROM Releases R
 INNER JOIN cte_Releases ON cte_Releases.ParentReleaseID = R.ReleaseId
) 
INSERT INTO @RootReleases 
SELECT max(ReleaseId) as ReleaseId, min(ReleaseId) as RootReleaseId FROM cte_Releases

SET @ctr = @ctr + 1
END

这段代码的目的是建立一个表,将记录与其最远的父记录连接起来,并将其插入到一个表中,以便在查询的其他地方引用。

4

1 回答 1

0

我没有要测试的数据,所以告诉我如果你按照这些思路运行会发生什么。应该可以使用 group by 和聚合。如果您提供示例数据,我可能会提供更多帮助。

     DECLARE @RootReleases table (ReleaseId int, RootReleaseId int)

;  WITH cte_Releases
( 
  ReleaseId,
  Name, 
  ParentReleaseID

) 
AS( 
  SELECT  
   ReleaseId, 
   Name,
   ParentReleaseID

  FROM Releases
 -- Where ReleaseId = @ctr

 UNION ALL 

 SELECT  
  R.ReleaseId,
  R.Name,
  R.ParentReleaseID 
 FROM Releases R
 INNER JOIN cte_Releases ON cte_Releases.ParentReleaseID = R.ReleaseId
) 
INSERT INTO @RootReleases 
SELECT max(ReleaseId) as ReleaseId, min(ReleaseId) as RootReleaseId FROM cte_Releases
WHERE ReleaseId BETWEEN 1 AND 100000
GROUP BY ReleaseId
于 2012-08-24T19:42:18.317 回答