0
,我有以下數據在我的表獲取所有的父母在父子層次
ID NAME PARENTID STATUS
----------- ------------------------------ ----------- ------
1 Folder A 0 0
2 Folder B 1 0
3 Folder C 2 1
4 Folder D 1 0
5 Folder E 4 0
6 Folder G 5 0
7 Folder H 6 1
上面記載是從表[@temp。
[Name] - Folder Name
[ID] - Unique ID of folder in database (identity)
[ParentID] - Represents the parent of current folder.
查詢表中所填寫上面的數據:
DECLARE @Temp TABLE
(
[ID] INT IDENTITY(1, 1) ,
[NAME] VARCHAR(30) ,
[PARENTID] INT,
[STATUS] BIT
)
INSERT INTO @Temp
SELECT 'Folder A' ,
0, 0
UNION
SELECT 'Folder B' ,
1, 0
UNION
SELECT 'Folder C' ,
2, 1
UNION
SELECT 'Folder D' ,
1, 0
UNION
SELECT 'Folder E' ,
4, 0
UNION
SELECT 'Folder G' ,
5, 0
UNION
SELECT 'Folder H' ,
6, 1
我有以下查詢來獲取記錄,其中狀態= 1
SELECT *
FROM @Temp WHERE [STATUS]=1
這給下面的輸出
ID NAME PARENTID STATUS
----------- ------------------------------ ----------- ------
3 Folder C 2 1
7 Folder H 6 1
我的目標是獲取那些記錄,這些記錄是父代(直到parentid = 0)的記錄隨同上述查詢。即我想這個輸出包含文件夾C和文件夾H的父母:
ID NAME PARENTID STATUS
----------- ------------------------------ ----------- ------
1 Folder A 0 0
2 Folder B 1 0
3 Folder C 2 1
4 Folder D 1 0
5 Folder E 4 0
6 Folder G 5 0
7 Folder H 6 1
您能給出一個預期結果的例子,其中預期結果與源數據不一樣嗎? –