我正在尝试构建一个 CTE 或只是一些从一个表中获取层次结构数据并将其插入到另一个可能具有不同索引的表中的查询。我认为这很简单,但由于某种原因我被卡住了。我无法使用新播种的索引在“RequiredID”上正确读取输出。顺便说一句,我正在使用 SQL Server 2012。
下面我提供了概念验证代码来演示我的目标。实际的 SQL 更复杂,但这说明了这一点。
这是我到目前为止所得到的:
DECLARE @Table TABLE (ID INT, Code NVARCHAR(50), RequiredID INT);
INSERT INTO @Table (ID, Code, RequiredID) VALUES
(1, 'Physics', NULL),
(2, 'Advanced Physics', 1),
(3, 'Nuke', 2),
(4, 'Health', NULL);
DECLARE @DefaultSeed TABLE (ID INT, Code NVARCHAR(50), RequiredID INT);
WITH hierarchy
AS (
--anchor
SELECT t.ID , t.Code , t.RequiredID
FROM @Table AS t
WHERE t.RequiredID IS NULL
UNION ALL
--recursive
SELECT t.ID
, t.Code
, h.ID
FROM hierarchy AS h
JOIN @Table AS t
ON t.RequiredID = h.ID
)
INSERT INTO @DefaultSeed (ID, Code, RequiredID)
SELECT ID
, Code
, RequiredID
FROM hierarchy
OPTION (MAXRECURSION 10)
DECLARE @NewSeed TABLE (ID INT IDENTITY(10, 1), Code NVARCHAR(50), RequiredID INT)
--this is where I get stuck - I can't get the requiredID to read like below
INSERT INTO @NewSeed (Code, RequiredID)
SELECT Code, RequiredID
FROM @DefaultSeed
--I'm trying to get @NewSeed should read like the following...
[ID] [Code] [RequiredID]
10....Physics..........NULL
11....Health...........NULL
12....AdvancedPhysics..10
13....Nuke.............12
SELECT *
FROM @NewSeed
任何帮助将不胜感激!