如何知道所有可能的父級和子行鍼對特定的ID?想要知道所有可能的父母和子行對特定的ID?
例如有如下表:
MyTable的:
-----------------------------------------------------
| Id | PId | Description |
-----------------------------------------------------
| 1 | NULL | A is Parent |
| 2 | 1 | B is Child of A |
| 3 | 2 | C is Child of B |
| 4 | NULL | D is Parent |
| 5 | NULL | E is Parent |
| 6 | 5 | F is Child of E |
-----------------------------------------------------
想知道的所有可能的父母和孩子,當通spesific ID
例如
CASE-01:
當@ MyLookupId = 2 OR @ MyLookupId = 1 OR @ MyLookupId = 3一個從他們然後結果應該是,
-------
| Id |
-------
| 1 |
| 2 |
| 3 |
-------
CASE-02:
當@ MyLookupId = 4然後結果應該是,
-------
| Id |
-------
| 4 |
-------
CASE-03:
當@ MyLookupId = 6然後結果應該是,
-------
| Id |
-------
| 5 |
| 6 |
-------
下面是表的SQL:
IF OBJECT_ID('tempdb.dbo.#MyTable', 'U') IS NOT NULL DROP TABLE #MyTable;
SELECT * INTO #MyTable FROM (
SELECT (1)Id, (NULL)PId, ('A IS Parent')Description UNION ALL
SELECT (2)Id, (1)PId, ('B IS Child of A')Description UNION ALL
SELECT (3)Id, (2)PId, ('C IS Child of B')Description UNION ALL
SELECT (4)Id, (NULL)PId, ('D IS Parent')Description UNION ALL
SELECT (5)Id, (NULL)PId, ('E IS Parent')Description UNION ALL
SELECT (6)Id, (5)PId, ('F IS Child of E')Description) AS tmp
SELECT * FROM #MyTable
哪裏有是「1名兒童6'說'7'。現在lookupid = 5,你也想要這個孩子嗎? – Utsav
5是父母,6是5的孩子,所以是應該在結果。 – Haseeb
使用CTE來確定位置......這裏有許多CTE案例或基本的CTE – maSTAShuFu