Home >Database >Mysql Tutorial >How to Insert Rows from One Table to Another in SQL Server?
Insert Rows into Existing Table using SQL Server
In SQL Server, the SELECT ... INTO ... syntax is primarily used to create a new table and insert data into it in a single statement. However, as the provided code illustrates, attempting to insert data into an existing table using this method will result in an error.
To successfully insert rows from one table into another, the recommended approach is to use the INSERT INTO statement. The basic syntax is as follows:
INSERT INTO <target_table> SELECT <column_list> FROM <source_table> WHERE <condition>;
In your case, to insert records from dbo.TableOne into dbo.TableTwo based on a specific condition, you would use the following statement:
INSERT INTO dbo.TableTwo SELECT col1, col2 FROM dbo.TableOne WHERE col3 LIKE @search_key;
Note that you need to specify the target columns in the INSERT statement, especially if dbo.TableTwo has additional columns not included in the SELECT statement. For instance:
INSERT INTO dbo.TableTwo (col1, col2) SELECT col1, col2 FROM dbo.TableOne WHERE col3 LIKE @search_key;
The above is the detailed content of How to Insert Rows from One Table to Another in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!