我正在尝试从多个表中获取数据并将它们导入到其他表中。目标使用身份标识,源表具有不同的标识。我需要从插入中获取新的身份 ID,并将它们添加到目标数据库中的另一个表中。这是我到目前为止所拥有的,但不知道如何让它工作。我尝试将 TMMYId 添加到 OUTPUT 中,但这不起作用。
DECLARE @MakeModels TABLE (MakeId int, ModelId int, YearId int, TMMYId int)
INSERT INTO @MakeModels (MakeId, ModelId, YearId, TMMYId)
SELECT MakeID, ModelID, YearID, T.id TypeMakeModelYear T
JOIN Fitment F
ON F.TMMYID = T.id JOIN PartToAppCombo P ON F.PartToAppComboID = P.ID
WHERE P.PartmasterID IN (SELECT PP.PartMasterID FROM PartPriceInv PP WHERE Discontinued
= 0)
DECLARE @MakeOutput TABLE (MakeId int, TMMYId int)
DECLARE @ModelOutput TABLE (ModelId int, TMMYId int)
DECLARE @YearOutput TABLE (YearId int, TMMYId int)
INSERT INTO Class1 (Name, Active)
OUTPUT INSERTED.Class1Id, MM.TMMYId INTO @MakeOutput
SELECT M.Description, 1 FROM Makes M JOIN @MakeModels MM ON M.id = MM.MakeId
WHERE NOT EXISTS (SELECT Class1Id FROM Class1 WHERE Name = M.Description )
INSERT INTO Class2 (Name, Active)
OUTPUT INSERTED.Class2Id, MM.TMMYId INTO @ModelOutput
SELECT M.Description, 1 FROM Models M JOIN @MakeModels MM ON M.id = MM.ModelId
WHERE NOT EXISTS (SELECT Class2Id FROM Class2 WHERE Name = M.Description)
INSERT INTO Class3 (Name, Active)
OUTPUT INSERTED.Class3Id, MM.TMMYId INTO @YearOutput
SELECT M.Description, 1 FROM Years M JOIN @MakeModels MM ON M.id = MM.YearId
WHERE NOT EXISTS (SELECT Class3Id FROM Class3 WHERE Name = M.Description)
INSERT INTO MMY (class1Id, class2Id, class3Id)
SELECT M.MakeId, MO.ModelId, Y.YearId FROM @MakeOutput M JOIN @ModelOutput MO ON
M.TMMYId = MO.TMMYId
JOIN @YearOutput Y ON MO.TMMYId = Y.TMMYId