Klingt wie, was Sie wollen, ist eine rekursive allgemeine Tabelle Ausdruck (CTE). Es ist gut, eine Hierarchie zu extrahieren.
Dieser Link sollte helfen: MSDN Recursive Queries Using Common Table Expressions Und ich habe das Hauptbeispiel unten kopiert.
USE AdventureWorks2008R2;
GO
WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(
-- Anchor member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
0 AS Level
FROM dbo.MyEmployees AS e
INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
Level + 1
FROM dbo.MyEmployees AS e
INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.BusinessEntityID AND edh.EndDate IS NULL
INNER JOIN DirectReports AS d
ON e.ManagerID = d.EmployeeID
)
-- Statement that executes the CTE
SELECT ManagerID, EmployeeID, Title, DeptID, Level
FROM DirectReports
INNER JOIN HumanResources.Department AS dp
ON DirectReports.DeptID = dp.DepartmentID
WHERE dp.GroupName = N'Sales and Marketing' OR Level = 0;
GO
Was ist Ihre erwartete Ausgabe? – Ravi
Welche Datenbank verwenden Sie? Bitte seien Sie spezifisch – Squirrel
Ich möchte alle mit A verbundenen IDs (A, B, C, D, E in diesem Fall) auswählen. Ich benutze MS SQL Server. Vielen Dank! – DennisL