我有一些存储以下数据的表格,这些数据并不是我实际拥有的,但是已经简化,以便更容易解释..
由于Table1是一个电子表格,我想将这些数据导入两个表(Table2和Table3)
我想为Table1中的每一行执行以下插入操作。
INSERT INTO Table2
(
UserID
,TestID
,StartTime
,EndTime
)
SELECT UserID
,TestID
,StartTime
,EndTime
FROM Table1
Declare @InsertedUserTestID INT
Set @id = SCOPE_IDENTITY()
-- Do this twice (once for Question1 and the second for Question2)
INSERT INTO Table3
(
UserTestID
,QuestionID
,AnswerID
)
SELECT
@id
,QuestionID1
,AnswerToQuestion1
FROM Table1
我读到我可以使用OUTPUT来使用插入的ID,但它不起作用,因为它不允许我选择那些不用于插入Table2的列。
INSERT INTO Table2
(
UserID
,TestID
,StartTime
,EndTime
)
OUTPUT Inserted.UserTestID
INTO Table3(Inserted.UserTestID, QuestionID1, AnswerToQuestion1)
SELECT UserID
,TestID
,StartTime
,EndTime
FROM Table1
有没有办法实现这个目标?或者我应该首先从Table1插入到Table2,然后使用Table1和Table2插入表3?
答案 0 :(得分:2)
马丁是对的 - 使用MERGE就可以了。如果你没有INSERT的两个行条目,你可以在一个语句中完成所有操作 - 因此你可以转储到临时表并执行以下操作:
CREATE TABLE #answers (UserTestID INT, QuestionID1 INT, AnswerID1 INT, QuestionID2 INT, AnswerID2 INT);
MERGE Table2
USING
(
SELECT UserID
,TestID
,StartTime
,EndTime
,QuestionID1
,AnswerToQuestion1
,QuestionID2
,AnswerToQuestion2
FROM Table1
) src ON (1=0)
WHEN NOT MATCHED THEN INSERT (UserID, TestID, StartTime, EndTime)
VALUES (src.UserID, src.TestID, src.StartTime, src.EndTime
OUTPUT Inserted.UserTestID, src.QuestionID1, src.AnswerID1, src.QuestionID2, src.AnswerID2
INTO #answers(UserTestID, QuestionID1, AnswerID1, QuestionID2, AnswerID2);
INSERT INTO Table3
(
UserTestID
,QuestionID
,AnswerID
)
SELECT UserTestID
,QuestionID1
,AnswerID1
FROM #answers
UNION
SELECT UserTestID
,QuestionID2
,AnswerID2
FROM #answers;