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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 18:23:43296browse

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

Inserting Rows from One Table into an Existing Table in SQL Server

Problem:

You're attempting to populate an existing table, dbo.TableTwo, with data from another table, dbo.TableOne, using the SELECT ... INTO ... statement within a stored procedure. However, you're encountering an error because dbo.TableTwo already exists.

Solution:

The SELECT ... INTO ... statement is designed to create a new table, not insert data into an existing one. To insert multiple rows from dbo.TableOne into dbo.TableTwo, you can use the INSERT statement as follows:

INSERT INTO dbo.TableTwo
SELECT col1, col2
FROM dbo.TableOne
WHERE col3 LIKE @search_key

Explanation:

The INSERT INTO statement specifies the destination table, dbo.TableTwo, where the new rows will be added. The SELECT clause retrieves the data from dbo.TableOne, including only the specified columns, col1 and col2. The WHERE clause limits the data to rows where col3 matches the value stored in the @search_key parameter.

Note:

If dbo.TableTwo already has more than two columns, you need to specify the column names explicitly in the INSERT statement, as shown below:

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 into Another Existing Table in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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