Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do this by using <code>MERGE</code> instead of insert:</p> <p>so replace this</p> <pre><code>INSERT INTO ReportOption (field1, field2...) OUTPUT @ReportOption.PracticeId, --&gt; this is the field I don't know how to get inserted.ReportOptionId INTO @PracticeReportOption (PracticeId, ReportOptionId) SELECT field1, field2 FROM @ReportOption </code></pre> <p>with </p> <pre><code>MERGE INTO ReportOption USING @ReportOption AS temp ON 1 = 0 WHEN NOT MATCHED THEN INSERT (field1, field2) VALUES (temp.Field1, temp.Field2) OUTPUT temp.PracticeId, inserted.ReportOptionId, inserted.Field1, inserted.Field2 INTO @PracticeReportOption (PracticeId, ReportOptionId, Field1, Field2); </code></pre> <p>The key is to use a statement that will never be true (1 = 0) in the merge statement, so you will always perform the insert, but have access to fields in both the source and destination tables.</p> <hr> <p>Here is the entire code I used to test it:</p> <pre><code>CREATE TABLE ReportOption (ReportOptionID INT IDENTITY(1, 1), Field1 INT, Field2 INT) CREATE TABLE Practice (PracticeID INT IDENTITY(1, 1), Field1 INT, Field2 INT) CREATE TABLE PracticeReportOption (PracticeReportOptionID INT IDENTITY(1, 1), PracticeID INT, ReportOptionID INT, Field1 INT, Field2 INT) INSERT INTO Practice VALUES (1, 1), (2, 2), (3, 3), (4, 4) MERGE INTO ReportOption r USING Practice p ON 1 = 0 WHEN NOT MATCHED THEN INSERT (field1, field2) VALUES (p.Field1, p.Field2) OUTPUT p.PracticeId, inserted.ReportOptionId, inserted.Field1, inserted.Field2 INTO PracticeReportOption (PracticeId, ReportOptionId, Field1, Field2); SELECT * FROM PracticeReportOption DROP TABLE ReportOption DROP TABLE Practice DROP TABLE PracticeReportOption </code></pre> <hr> <p>More reading, and the source of all that I know on the subject is <a href="http://sqlblog.com/blogs/adam_machanic/archive/2009/08/24/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge.aspx">Here</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload