Output columns not in destination table?

Posted by lance on Stack Overflow See other posts from Stack Overflow or by lance
Published on 2010-05-14T16:10:17Z Indexed on 2010/05/14 21:04 UTC
Read the original article Hit count: 206

SUMMARY:
I need to use an OUTPUT clause on an INSERT statement to return columns which don't exist on the table into which I'm inserting. If I can avoid it, I don't want to add columns to the table to which I'm inserting.

DETAILS:
My FinishedDocument table has only one column. This is the table into which I'm inserting.

FinishedDocument
-- DocumentID

My Document table has two columns. This is the table from which I need to return data.

Document
-- DocumentID
-- Description

The following inserts one row into FinishedDocument. Its OUTPUT clause returns the DocumentID which was inserted. This works, but it doesn't give me the Description of the inserted document.

INSERT INTO FinishedDocument
OUTPUT INSERTED.DocumentID
SELECT DocumentID
FROM Document
WHERE DocumentID = @DocumentID

I need to return from the Document table both the DocumentID and the Description of the matching document from the INSERT.

What syntax do I need to pull this off? I'm thinking it's possible only with the one INSERT statement, by tweaking the OUTPUT clause (in a way I clearly don't understand)?

Is there a smarter way that doesn't resemble the path I'm going down here?

EDIT: SQL Server 2005

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about insert