3

Good day,

I was wondering if it is possible to use an INSERT-OUTPUT statement in such a way as to provide the value(s) for another, outer, INSERT statement. That way values can be added to an entity table and an intersection table in a single statement - I hope I'm wording this effectively. For example:

INSERT INTO [#tblIntersect] ([Entity1ID], [Entity2ID])
VALUES
(
    INSERT INTO [#tblEntity1] ([Value])
    OUTPUT [inserted].[ID] AS [entity1ID], @entity2ID AS [entity2ID]
    VALUES ('One')
)

So the inner INSERT-OUTPUT statement will add a new entity to table #tblEntity1. The new entity's ID (which is set as IDENTITY(1, 1) will then be returned through the OUTPUT statement, along with a static value (which I already have in my code), to provide the two values for the outer INSERT statement.

The reason I think it might be possible is because execution of the inner INSERT-OUTPUT statement on its own returns a table anyway, and such output can usually be used to provide values for INSERT statements.

Obviously this example doesn't work; I was hoping it's just a simple syntax problem.

Thank you in advance for any comments and advice.

5
  • something like last-insert-id does not work in this case to fetch it again and use the select result of it for another insert? Commented Apr 19, 2012 at 15:47
  • it probably would, I was just trying to write the shortest query with the least separate statements :P Commented Apr 19, 2012 at 15:57
  • which database software is used? Commented Apr 19, 2012 at 16:00
  • added the tsql tag, if INSERT OUPUT is used. Commented Apr 19, 2012 at 16:03
  • i'm using sql 2008 and c# - it's a winforms application Commented Apr 19, 2012 at 16:15

1 Answer 1

1

Your requirement is possible according to the documentation.

Assuming #tblIntersect has two matching id columns this should work

INSERT INTO [#tblEntity1] ([Value])
OUTPUT [inserted].[ID] AS [entity1ID], @entity2ID AS [entity2ID]
   INTO #tblIntersect
VALUES ('One')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.