我有一个SQL表,其中包含按层次结构组织的记录,如下所示:
ID Item OtherColumns ParentID
1 a blah NULL
2 b blah 1
3 c blah 2
4 d blah 3
5 e blah 3
6 f blah 3
7 g blah 4
8 h blah 4
9 i blah 4
10 j blah 4
11 k blah 6
12 l blah 6
13 m blah 6
14 n blah 6
图形上,层次结构是
a
--b
----c
-------d
----------g
----------h
----------i
----------j
-------e
-------f
----------k
----------l
----------m
----------n
我有一个SQL脚本,它接受一个parentID参数并返回该节点的所有子节点。
我从批处理文件中的递归函数调用脚本,并按照结构的顺序打印出项目,但我不知道如何创建一个反映这个的文件夹结构
我的批次是
@echo off
setlocal enabledelayedexpansion
set Id=1
call :CreateSubDirectories !Id! 1
goto eof
:CreateSubDirectories
for /f "tokens=1,2,*" %%i IN ('sqlcmd -S MyServer\MyInstance -d myDatabase -U myUser -P myPassword -i C:\Path\to\my\script.sql -v parentId^=%~1! -h -1') DO (
echo %%i
call :CreateSubDirectories %%i
)
:eof
endlocal
所以打印出来
a
b
c
d
g
h
i
j
e
f
k
l
m
n
但是,如果我要在循环中添加mkdir,则所有文件夹都将在同一级别创建。我怎样才能创建上面表示的文件夹结构?
答案 0 :(得分:1)
针对CTE输出运行mkdir
DECLARE @foo TABLE
(ID int, Item varchar(100), OtherColumns varchar(20), ParentID int)
INSERT @foo VALUES
(1 ,'a', 'blah', NULL),
(2 ,'b', 'blah', 1 ),
(3 ,'c', 'blah', 2 ),
(4 ,'d', 'blah', 3 ),
(5 ,'e', 'blah', 3 ),
(6 ,'f', 'blah', 3 ),
(7 ,'g', 'blah', 4 ),
(8 ,'h', 'blah', 4 ),
(9 ,'i', 'blah', 4 ),
(10 ,'j', 'blah', 4 ),
(11 ,'k', 'blah', 6 ),
(12 ,'l', 'blah', 6 ),
(13 ,'m', 'blah', 6 ),
(14 ,'n', 'blah', 6 );
WITH Hierarchy AS
(
SELECT ID, FolderPath = Item, OtherColumns, ParentID, 1 AS Level FROM @foo WHERE ParentID IS NULL
UNION ALL
SELECT [@foo].ID,
LEFT(CONCAT(Hierarchy.FolderPath, '\', [@foo].Item), 100),
[@foo].OtherColumns,
[@foo].ParentID,
Level + 1
FROM
Hierarchy JOIN @foo ON [@foo].ParentID = Hierarchy.ID
)
SELECT FolderPath FROM Hierarchy ORDER BY Hierarchy.Level;
给出
a
a\b
a\b\c
a\b\c\d
a\b\c\e
a\b\c\f
a\b\c\f\k
a\b\c\f\l
a\b\c\f\m
a\b\c\f\n
a\b\c\d\g
a\b\c\d\h
a\b\c\d\i
a\b\c\d\j