如何避免在此处使用while循环?

时间:2012-08-24 18:37:39

标签: sql loops stored-procedures while-loop

作为一个从未接受过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

此代码的目的是构建一个表,将记录与其最近的父记录连接起来,并将其插入到表中,以便在查询的其他位置引用。

1 个答案:

答案 0 :(得分:0)

我没有要测试的数据所以请告诉我如果你沿着这些方向运行会发生什么。 应该可以使用group by和aggregate。 如果您提供样本数据,我可以提供更多帮助。

     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