Skip to main content

Posts

Showing posts from September, 2015

Is it possible to for SQL Output clause to return a column not being inserted?

You can do this by using   MERGE   instead of insert: so replace this INSERT INTO ReportOption ( field1 , field2 ...) OUTPUT @ ReportOption . PracticeId , --> this is the field I don't know how to get inserted . ReportOptionId INTO @ PracticeReportOption ( PracticeId , ReportOptionId ) SELECT field1 , field2 FROM @ ReportOption with 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 ); 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. Here is the entire code I used to test it: CREATE TABLE Repo