2

I'm trying to insert 2 records into 2 tables by using a subquery, but it gives me a syntax error.

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'INSERT'. Msg 102, Level 15, State 1, Line 4 Incorrect syntax near ')'.

The query that I'm trying to execute is

INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId]) 
VALUES 
(
   (INSERT INTO [FileTransformations] OUTPUT INSERTED.FileTransformationId DEFAULT VALUES),
   2
)

Is this possible?

3

1 Answer 1

1

You need to store the output in a variable first. So, I think you want something like this:

DECLARE @variable TABLE (value INT)--change type depending on your need

INSERT INTO [FileTransformations] 
OUTPUT INSERTED.FileTransformationId INTO @variable(value)
VALUES(.....)

INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId]) 
SELECT value, 2 FROM @variable

See How do I use an INSERT statement's OUTPUT clause to get the identity value? for more info on using output variables and Insert into table from table variable? for then inserting from that table variable.

Another option, if you just want the id of the last inserted record is to use scope_identity(). So you could write the above as:

INSERT INTO [FileTransformations] 
VALUES(.....)

INSERT INTO [Files] ([FileTransformationId],[FileTypeEnumId]) 
VALUES scope_identity(), 2
Sign up to request clarification or add additional context in comments.

6 Comments

if I try to execute the insert statement with the into clause, it gives me the error Must declare the table variable "@variable", so i guess it needs to be a temp table or should it be possible for @variable to be a simple int variable?
@variable must be a table variable
Yes, I missed that @DenisRubashkin, not something I use often
@Ronald, yes, sorry. I got the syntax for the table variable output wrong
Any there any performance drawbacks for using the table variable?
|

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.