I have some tables that store the following data, which is not exactly what I actually have but is simplified so that it's easier to explain..
Table1
- UserID (FK)
- TestID (FK)
- StartTime
- EndTime
- QuestionID1
- AnswerToQuestion1
- QuestionID2
- AnswerToQuestion2
Since Table1 is a spreadsheet, I want to import this data into two tables (Table2 and Table3)
Table2
- UserTestID (PK)
- UserID
- TestID
- StartTime
- EndTime
Table3
- UserTestID (FK)
- QuestionID (FK)
- AnswerID (FK)
What I want to do is ...
I want to do the following insertion for each row in 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
What I've tried
I read that I can use OUTPUT to use the inserted ID but it doesn't work because it doesn't let me select those columns that are not used to insert into Table2.
INSERT INTO Table2
(
UserID
,TestID
,StartTime
,EndTime
)
OUTPUT Inserted.UserTestID
INTO Table3(Inserted.UserTestID, QuestionID1, AnswerToQuestion1)
SELECT UserID
,TestID
,StartTime
,EndTime
FROM Table1
Is there any way to achieve this? Or should I do the insertion from Table1 to Table2 first, and then use both Table1 and Table2 to insert into Table3?