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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 How Do I Use OUTPUT to Populate Two Tables
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

1 Posts

Posted - 07/15/2013 :  16:50:20  Show Profile  Reply with Quote
I have a staging table:

personID int,
testDate smallDateTime,
testScore float,
Q1 int,
Q1 int,

that needs to populate two production tables:

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

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:

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 is there a correct way to do it?

James K
Flowing Fount of Yak Knowledge

3873 Posts

Posted - 07/15/2013 :  20:30:38  Show Profile  Reply with Quote
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

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 07/16/2013 :  01:16:54  Show Profile  Reply with Quote
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
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000