Home > Database > Mysql Tutorial > How to Insert Rows from One Table to Another in SQL Server?

How to Insert Rows from One Table to Another in SQL Server?

Mary-Kate Olsen
Release: 2025-01-05 09:36:41
Original
193 people have browsed it

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>;
Copy after login

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;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template