While Exists (Select * From Col Where Depth Is Null)
Update T
Set T.Depth = P.Depth + 1,
T.Lineage = P.Lineage + LTrim(Str(T.ParentId, 6, 0)) + '/'
From Col T
Join Col P On T.ParentId = P.Id
Where
P.Depth >= 0
And P.Lineage Is Not Null
And T.Depth Is Null
答案 0 :(得分:-2)
看起来你正在尝试进行递归查询,标准的方法是使用CTE:
;WITH rec AS(
SELECT c.Id, c.Depth, CAST(c.Id AS varchar(MAX) + '/' AS Lineage
FROM Col c
WHERE c.ParentId IS NULL
UNION ALL
SELECT c1.Id, rec.Depth + 1, rec.Lineage + CAST(c1.id as varchar(10)) + '/'
FROM rec
INNER JOIN Col c1 on rec.Id = c1.ParentId
WHERE rec.Depth < 100 --Limit the recursion, set this to what is appropriate for your data
)
--SELECT * FROM rec --Use this first to see if the data is correct, then:
UPDATE T
SET T.Depth = r.Depth, T.Lineage = r.Lineage
FROM Col T
INNER JOIN rec r ON T.Id = r.Id
有关CTE的更多信息,您可以查看this technet link。