Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT-OUTPUT including column from other table

I have a stored procedure that needs to insert into three different tables, but I need to get the ID generated from the one input and use that to insert into the next table. I'm familiar with the INSERT-OUTPUT construct, but I'm not sure how to go about using it in this particular case.

DECLARE @guids TABLE ( [GUID] UNIQUEIDENTIFIER ); DECLARE @contacts TABLE ( [ContactID] INT, [GUID] UNIQUEIDENTIFIER ); DECLARE @mappings TABLE ( [TargetID] INT, [GUID] UNIQUEIDENTIFIER );  INSERT @guids ( [GUID] ) ...  INSERT [Contacts] ( [FirstName], [LastName], [ModifiedDate] ) OUTPUT [inserted].[ContactID], g.[GUID] INTO @contacts SELECT [First_Name], [Last_Name], GETDATE() FROM [SourceTable] s JOIN @guids g ON s.[GUID] = g.[GUID]  INSERT [TargetTable] ( [ContactID], [License], [CreatedDate], [ModifiedDate] ) OUTPUT [inserted].[TargetID], c.[GUID] INTO @mappings SELECT c.[ContactID], [License], [CreatedDate], [CreatedDate] FROM [SourceTable] s JOIN @contacts c ON s.[GUID] = c.[GUID]   INSERT [Mappings] ( [TargetID], [SourceGUID] ) SELECT [TargetID], [GUID] FROM @mappings 

But I get the following errors:

The multi-part identifier "g.GUID" could not be bound.

The multi-part identifier "c.GUID" could not be bound.

I'll get similar errors if I use s.GUID instead. Is it possible to do a kind of join in the OUTPUT clause?

like image 761
p.s.w.g Avatar asked Mar 07 '13 21:03

p.s.w.g


People also ask

How do I insert a column from one table to another?

INSERT INTO SELECT Syntax Copy only some columns from one table into another table: INSERT INTO table2 (column1, column2, column3, ...)

How do you insert the result of a query into a table?

To create an Insert Results query From the Query Designer menu, point to Change Type, and then click Insert Results. In the Choose Target Table for Insert Results Dialog Box, select the table to copy rows to (the destination table).

How do I get data from another table in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.


1 Answers

I'm not sure if that is the best option, but it seems you can do the trick using MERGE :

MERGE [Contacts]  trgt USING  (     SELECT [First_Name], [Last_Name], g.[GUID] as [GUID]   FROM [SourceTable] s   JOIN @guids g ON s.[GUID] = g.[GUID] )src ON (1=0) WHEN NOT MATCHED THEN INSERT ( [FirstName], [LastName], [ModifiedDate] )  VALUES (src.[First_Name],src.[Last_Name], GETDATE()) OUTPUT [inserted].[ContactID], src.[GUID] INTO @contacts 
like image 165
a1ex07 Avatar answered Sep 30 '22 06:09

a1ex07