作为一个从未从任何人那里得到过 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
这段代码的目的是建立一个表,将记录与其最远的父记录连接起来,并将其插入到一个表中,以便在查询的其他地方引用。