Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output columns not in destination table?

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

like image 943
lance Avatar asked Sep 03 '25 03:09

lance


2 Answers

Look at Example A:

DECLARE @temp TABLE (DocumentID int)

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

SELECT Document.DocumentId, Document.Description
FROM @temp AS t
INNER JOIN Document 
    ON t.DocumentID = Document.DocumentID
like image 142
Cade Roux Avatar answered Sep 07 '25 07:09

Cade Roux


I wonder if you can backdoor it like this (should it concern me that I'd actually consider doing it this way?):

;WITH r (DocumentID)
     AS (INSERT INTO FinishedDocument
         OUTPUT INSERTED.DocumentID
         SELECT DocumentID
           FROM Document
          WHERE DocumentID = @DocumentID)
 SELECT d.DocumentID, d.DocumentName
   FROM Document d
   JOIN r
     ON d.DocumentID = r.DocumentID

Your insert still uses the OUTPUT clause, but as an inline table that then links up to the Document to get your required info. Though, for some reason, I can't escape the feeling that this bastardizes the WITH clause hopelessly...

like image 40
SqlRyan Avatar answered Sep 07 '25 09:09

SqlRyan