SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

puffster
Starting Member

USA
1 Posts

Posted - 07/15/2013 :  16:50:20  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3744 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

visakh16
Very Important crosS Applying yaK Herder

India
52325 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
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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.06 seconds. Powered By: Snitz Forums 2000