我有一张表(下面的结构和示例数据)
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
答案 0 :(得分:0)
看一下你想要的代码
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