How can I make a SELECT inside an INSERT operation?
insert into tableX (a_id, b_id) VALUES ((SELECT service_id FROM tableY WHERE id = 10, 2));
But the server returns a syntax error, why?
SQL Error [156] [S0001]: Incorrect syntax near the keyword 'select'.
When executing a query in SQL and the editor throws back this error: Incorrect syntax near …'' That typically means you have used the wrong syntax for the query. This happens mostly when someone switched from one relational database to another relational database, from MySQL to MS SQL Server for example.
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.
Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.
While my original answer gave a working solution, I was actually wrong about the cause of the error. There is nothing wrong with using a scalar subquery inside a VALUES clause. The problem with the statement in the question is simply that one parenthesis is in the wrong place; the scalar subquery must be enclosed in parentheses.
This should work:
insert into tableX (a_id, b_id) VALUES ( (SELECT service_id FROM tableY WHERE id = 10) , 2 );
Original Answer
VALUES
can only be used in conjunction with literal values. However, literal values can be used in a subquery. Do this:
insert into tableX (a_id, b_id) SELECT service_id, 2 FROM tableY WHERE id = 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With