从多个标识插入到另一个表的输出

时间:2012-10-19 02:09:20

标签: sql-server-2005 declarative

我正在尝试从多个表中获取数据并将它们导入到其他表中。目标使用标识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

0 个答案:

没有答案