Is there a way to insert pre-set values and values I get from a select-query? For example:
INSERT INTO table1 VALUES ("A string", 5, [int]).
I have the value of "A string" and the number 5, but I've to find the [int] value from a select like this:
SELECT idTable2 FROM table2 WHERE ...
that gives me that id to put inside table1.
How to merge this into one statement?
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.
INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. 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.
INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.
Use an insert ... select
query, and put the known values in the select
:
insert into table1 select 'A string', 5, idTable2 from table2 where ...
just use a subquery right there like:
INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).
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