【发布时间】:2016-04-22 03:18:40
【问题描述】:
我在这个问题上遇到了困难。我已经看到了一些关于如何从给定父项的自引用表中获取所有子记录的示例,甚至如何获取子记录的父项。
我要做的是返回一条记录以及给定 ID 的所有子记录。
为了说明这一点 - 我有一个公司层次结构。地点:
#Role Level#
--------------------
Corporate 0
Region 1
District 2
Rep 3
我需要的是一个过程,(1) 确定记录的级别,(2) 检索该记录和所有子记录。
作为一个地区的想法可以看到一个地区的所有地区和代表,地区可以看到他们的代表。代表只能看到自己。
我有桌子:
ID ParentId Name
-------------------------------------------------------
1 Null Corporate HQ
2 1 South Region
3 1 North Region
4 1 East Region
5 1 West Region
6 3 Chicago District
7 3 Milwaukee District
8 3 Minneapolis District
9 6 Gold Coast Dealer
10 6 Blue Island Dealer
我该怎么做:
CREATE PROCEDURE GetPositions
@id int
AS
BEGIN
--What is the most efficient way to do this--
END
GO
例如@id = 3 的预期结果,我想返回:
3, 6, 7, 8, 9, 10
如果有任何帮助或想法,我将不胜感激。
【问题讨论】:
-
预期的结果是什么?
-
我更新了问题以显示预期结果。
标签: sql sql-server stored-procedures