When you do an insert ... output
, the "output" part can only output whatever was inserted by the "insert" part. You can't reference data from the "inserting" table.
You do insert into tbl_tours(TimeFrom)
. So you're only inserting a single column - the TimeFrom column, and the tour_id column will be automatically inserted, so that's available too. But then you try to use 4 columns in the output list. Where would these extra two columns come from?
One way to do this in a single step is to use the merge
statement, which can get data from the "inserting" source, not just the "inserted" table. Since you know you always want to do an insert, you can join on 1 = 0
:
merge tbl_tours
using @tmpTable tmp on 1 = 0
when not matched then
insert (TimeFrom)
values (tmp.TimeFrom)
output inserted.tourId,
tmp.dispatchingId,
inserted.timeFrom, -- or tmp.timeFrom, doesn't matter which
tmp.TimeTo
into tbl_tourData (tour_fk, dispatchId, timeFrom, timeTo);
I should add: This is only possible because you don't actually have a foreign key defined from tbl_tourData
to tbl_Tours
. You probably do intend to have one given your column name. An output clause can't output into a table with a foreign key (or a primary key with a foreign key to it), so this approach won't work at all if you ever decide to actually create that foreign key. You'll have to do it in two steps. Either per Gordon's answer (insert and join), or by creating a whole new temp table matching the schema of tbl_tourData
, outputting everything into that using merge
, and then dumping the second temp table into the real tbl_tourData
.