Although there is no reason (apart maybe from aesthetics) to use INSERT INTO SELECT
when inserting a single row in a table, is there any difference between using this and INSERT INTO VALUES
?
S.No. INSERT INTO SELECT statement in SQL Server is used to copy data from the source table and insert it into the destination table. The SELECT INTO statement in SQL Server is used to copy data from one (source) table to a new table. INSERT INTO SELECT requires the destination table to be pre-defined.
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.
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.
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.
Using the INSERT INTO ... SELECT
approach allows you to pick your values from another table, based on some criteria.
INSERT INTO dbo.TargetTable(Col1, Col2, ...., ColN) SELECT Col1, Col2, ..., ColN FROM dbo.SourceTable WHERE (some condition)
That might be a bit easier and more readable to write, rather than having to retrieve 20 values from your source table, stash them into temporary variables, just so you can then call your INSERT INTO dbo.Destination(....) VALUES(......)
statement...
DECLARE @Value1 INT DECLARE @Value2 DATETIME .... DECLARE @ValueN INT SELECT @Value1 = Col1, @Value2 = Col2, .... @ValueN = ColN FROM dbo.SourceTable WHERE (some condition) INSERT INTO dbo.TargetTable(Col1, Col2, ...., ColN) VALUES(@Value1, @Value2, ....., @ValueN)
But in the end - it's just an INSERT
statement that inserts data - it's really just a matter of personal preference and which approach is easier / more convenient to use....
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