![](/img/trans.png)
[英]Recursive query for parent child hierarchy. Get descendants from a top node
[英]MSSQL Get Recursive Parent Title For Child Node
我有一張桌子(下面的結構和樣本數據)
declare @table table
(
PrimaryID BIGINT,
ParentID BIGINT NULL,
Title NVARCHAR(100) NULL,
HierID HIERARCHYID
)
INSERT INTO @table VALUES (100, NULL, 'Root', 0x52C0)
INSERT INTO @table VALUES (101, 100, 'Folder', 0x52D6)
INSERT INTO @table VALUES (102, 101, 'SubFolder', 0x52D6F0)
INSERT INTO @table VALUES (103, 102, 'Document', 0x52D6F580)
INSERT INTO @table VALUES (104, 101, 'Folder2', 0x52DA)
select * from @table
對於任何給定的PrimaryID-我想按順序生成所有標題的串聯列表
所需的輸入/輸出:
@input = 103
@output = \Root\Folder\Subfolder\Document
@input = 102
@output = \Root\Folder\Subfolder
@input = 104
@output = \Root\Folder\Folder2
我設法編寫了一個具有父子關系的遞歸CTE,並生成了標題列表,但是順序相反……例如,'\\ Document \\ SubFolder \\ Folder \\ Root',我想反過來。
提前致謝
JW
看看下面想要的代碼
DECLARE @Input NUMERIC = 104
DECLARE @Retstr VARCHAR(500) = ''
WHILE @Input > 0
BEGIN
DECLARE @GetValue VARCHAR(500) =''
DECLARE @ParentID NUMERIC = 0
SELECT @GetValue = ISNULL(Title,''),@ParentID = ISNULL(ParentID,0) FROM #table WHERE PrimaryID = @Input
IF(@GetValue != '')
BEGIN
IF(@Retstr!= '')
BEGIN
SET @Retstr = @GetValue + '\' + @Retstr
END
ELSE
BEGIN
SET @Retstr = @GetValue
END
END
SET @Input = @ParentID
END
IF(@Retstr!='')
BEGIN
SET @Retstr = '\' + @Retstr
END
PRINT @Retstr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.