Home >Database >Mysql Tutorial >How to Insert Data from One Table into Another Using a SQL Server Stored Procedure?

How to Insert Data from One Table into Another Using a SQL Server Stored Procedure?

DDD
DDDOriginal
2025-01-04 21:46:44781browse

How to Insert Data from One Table into Another Using a SQL Server Stored Procedure?

SQL Server: Inserting Rows into an Existing Table Using Stored Procedure

In SQL Server, selecting data from one table and inserting it into an existing table using a stored procedure requires a different approach from creating temporary tables. When attempting to use SELECT ... INTO ... to insert data into an existing table, you may encounter an error indicating that the table already exists.

To resolve this issue and insert rows from one table into another, the following steps must be taken:

  1. Utilize the INSERT statement instead of SELECT ... INTO .... This statement explicitly specifies the target table for data insertion.
  2. After the INSERT statement, specify the columns to be inserted into the target table if they differ from the source table.
  3. Use the SELECT statement as the data source, retrieving the desired columns from the source table.
  4. Include a WHERE clause to filter the data being inserted based on specific criteria.

Here's an example that inserts rows from dbo.TableOne into dbo.TableTwo based on a specified search key:

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

By following these steps, you can successfully insert rows from one table into an existing table using a stored procedure in SQL Server.

The above is the detailed content of How to Insert Data from One Table into Another Using a SQL Server Stored Procedure?. 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