我正在升级旧版应用程序,我需要查找表中某些行的父项数。
我正在考虑为此使用声明的程序,但我无法弄清楚如何使其工作。
基本上你有一个id和父
的表= id = parent =
= 0 = 0 =
= 1 = 0 =
= 2 = 1 =
= 3 = 1 =
= 4 = 2 =
ID是唯一的,并且parent是可变的,具体取决于用于创建该条目的内容,但它始终匹配具有匹配ID的行
我想要实现的是调用一个将所有匹配的父数字作为简单的可迭代结果集返回的过程。
所以如果我要做getAllParents(4)它应该给我2,1,0
我失败的循环尝试让我到目前为止
CREATE PROCEDURE getNumberOfParents @start int @current int
as
begin
SELECT parent FROM test where id=@start
if(parent > 0)
begin
set @current = @current + 1;
set @current = @current + getNumberOfParents(parent,@current);
end
end
由于限制,我不能使用额外的表来实现这一目标,否则我会很容易。然而,我可以制作可以在方法退出后清理的临时表。
答案 0 :(得分:3)
通过使用递归CTE
:
DECLARE @lookupId INT = 4
;WITH ParentsCTE AS (
SELECT id, parent
FROM #mytable
WHERE id = @lookupId
UNION ALL
SELECT m.id, m.parent
FROM #mytable AS m
INNER JOIN ParentsCTE AS p ON m.id = p.parent
WHERE m.id <> m.parent
)
SELECT parent
FROM ParentsCTE
上述CTE
的锚点成员:
SELECT id, parent
FROM #mytable
WHERE id = @lookupId
返回&#39;查找ID&#39;的直接父。
递归成员:
SELECT m.id, m.parent
FROM #mytable AS m
INNER JOIN ParentsCTE AS p ON m.id = p.parent
WHERE m.id <> m.parent
继续在层次结构中添加父级,直到根节点(m.id <> m.parent
谓词检测到此内容)已到达。
答案 1 :(得分:2)
DECLARE @Table TABLE (id INT, parent INT)
INSERT INTO @Table VALUES
(0 , 0),
(1 , 0),
(2 , 1),
(3 , 1),
(4 , 2)
-- Id you want all the parents for
DECLARE @ParentsFor INT = 4
;with parents as
(
select ID, parent
from @Table
where parent IS NOT NULL
union all
select p.ID, t.parent
from parents p
inner join @Table t on p.parent = t.ID
and t.ID <> t.parent
)
select Distinct
STUFF((SELECT ',' + Cast(parent AS VarChar(10))
FROM parents
WHERE ID = @ParentsFor
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'')
FROM parents
2,1,0
SQL FIDDLE
答案 2 :(得分:0)
<强> Fiddle Demo Here 强>
尝试:
declare @id varchar(max)=''
declare @getid int=4
while @getid>0
begin
select @id=@id+cast(parent as varchar(10))+',' from tab_1
where id=@getid
select @getid=parent from tab_1 where id=@getid
end
select @id
答案 3 :(得分:-1)