我正在尝试构建一个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
非常感谢任何帮助!
答案 0 :(得分:2)
您可以将OUTPUT与Merge结合使用,以获取从ID到新ID的映射。
基本部分:
--this is where you got stuck
Declare @MapIds Table (aOldID int,aNewID int)
;MERGE INTO @NewSeed AS TargetTable
Using @DefaultSeed as Source on 1=0
WHEN NOT MATCHED then
Insert (Code,RequiredID)
Values
(Source.Code,Source.RequiredID)
OUTPUT Source.ID ,inserted.ID into @MapIds;
Update @NewSeed Set RequiredID=aNewID
from @MapIds
Where RequiredID=aOldID
以及整个例子:
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)
Declare @MapIds Table (aOldID int,aNewID int)
;MERGE INTO @NewSeed AS TargetTable
Using @DefaultSeed as Source on 1=0
WHEN NOT MATCHED then
Insert (Code,RequiredID)
Values
(Source.Code,Source.RequiredID)
OUTPUT Source.ID ,inserted.ID into @MapIds;
Update @NewSeed Set RequiredID=aNewID
from @MapIds
Where RequiredID=aOldID
/*
--@NewSeed should read like the following...
[ID] [Code] [RequiredID]
10....Physics..........NULL
11....Health...........NULL
12....AdvancedPhysics..10
13....Nuke.............12
*/
SELECT *
FROM @NewSeed