Example tables for SQL Server.
- MainRecords (
id, record) - AuxRecords (
mainRecords_id, record) - SourceRecords (
record1, record2)
MainRecords.id is a self incrementing primary identity key.
Is it possible to select from SourceRecords and insert into MainRecords and AuxRecords at the same time such that MainRecords.record = record1, AuxRecords.record = record2, and AuxRecords.mainRecords_id = MainRecords.id all in a single statement?
EDIT:
Based on tip from below, I tried this…
DECLARE @MainRecords table(id int PRIMARY KEY IDENTITY, record varchar(5))
DECLARE @AuxRecords table(mainRecords_id int, record varchar(5))
DECLARE @SourceRecords table(record1 varchar(5), record2 varchar(5))
INSERT @SourceRecords VALUES ('a', 'a')
INSERT @SourceRecords VALUES ('a', 'b')
INSERT @SourceRecords VALUES ('a', 'c')
INSERT @SourceRecords VALUES ('b', 'a')
INSERT @SourceRecords VALUES ('b', 'b')
INSERT @SourceRecords VALUES ('b', 'c')
INSERT @SourceRecords VALUES ('c', 'a')
INSERT @SourceRecords VALUES ('c', 'b')
INSERT @SourceRecords VALUES ('c', 'c')
INSERT INTO @MainRecords (record)
OUTPUT inserted.id, @SourceRecords.record2
INTO @AuxRecords (mainRecords_id, record)
SELECT record1 FROM @SourceRecords
select * from @MainRecords
select * from @AuxRecords
But unfortunately get error:
Msg 137, Level 16, State 1, Line 16
Must declare the scalar variable "@SourceRecords".
If I change those table type variables into real tables I get the error:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "SourceRecords.record2" could not be bound.
Below works fine, but obviously it isn’t a complete solution. I’m just showing it to demonstrate that my syntax is correct.
INSERT INTO @MainRecords (record)
OUTPUT inserted.id --, @SourceRecords.record2
INTO @AuxRecords (mainRecords_id) --, record)
SELECT record1 FROM @SourceRecords
So… unless there is some trick I am missing, it seems like OUTPUT is a dead end solution for this problem.
The other suggestions of creating views or empty tables with triggers are not a “single statement” solution to the problem. Moreover, they add obscurity, whereas adding some extra columns and using a stored procedure is equally complex but more obvious and straightforward.
community wiki
there isn’t enough info in the question to write code to solve the question. So, here is a “generic” output clause example, which does not relate at all to this question, other than to show how OUTPUT can be used:
this will delete, insert, and return multiple rows in a single statement
OUTPUT: