Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 How Do I Use OUTPUT to Populate Two Tables

Author  Topic 

puffster
Starting Member

1 Post

Posted - 2013-07-15 : 16:50:20
I have a staging table:

stagingTestResults
(
personID int,
testDate smallDateTime,
testScore float,
Q1 int,
Q1 int,
...
)

that needs to populate two production tables:

dimStudentTestResults
(
testID int identity (1,1),
personID int,
testDate smallDateTime
)

factStudentTestResults
(
testID int (FK for the testID above),
testScore float
Q1 int,
Q2 int,
...
)

I want to use Output to capture the testID identity that is created in dimStudentTestResults, to use in factStudentTestResults. Is it possible to match the results of the Output values with the staging values, to put into the factStudentTestResults table? The best I've come up with is something like below, which gives me the error below it:

Insert
Into dimStudentTestResults (personID, testDate)
Output inserted.testID
Into factStudentTestResults_AP (testID, testScore, Q1, Q2)
Select personID, testDate, testScore, Q1, Q2
From staging_testResults_ap

The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.

This makes complete sense to me...so is there a correct way to do it?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-07-15 : 20:30:38
Insert the data into an intermediate temp table or table variable. Do a second insert into the factStudentTestResults table by joining that intermediate table to the stagingTestResults table.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-16 : 01:16:54
I think this is what you're after

Insert Into dimStudentTestResults (personID, testDate)
Select personID, testDate
From staging_testResults_ap

Insert Into factStudentTestResults_AP (testID, testScore, Q1, Q2)
select d.testID, s.testScore, s.Q1, s.Q2
from dimStudentTestResults d
inner join staging_testResults_ap s
on s.testDate = d.testDate
AND s.personID = d.personID


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -