Home >Database >Mysql Tutorial >How to Insert Multiple Rows into a Table Using a Subquery in SQL Server?

How to Insert Multiple Rows into a Table Using a Subquery in SQL Server?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 04:49:39979browse

How to Insert Multiple Rows into a Table Using a Subquery in SQL Server?

Inserting Values into a Table Using a Subquery with Multiple Results

Problem:

You have two SQL Server tables, "article" and "prices", and you want to insert entries into the "prices" table based on a specific set of IDs retrieved from the "article" table. However, your query results in an error because the subquery returns more than one value.

Answer:

To successfully insert values when the subquery returns multiple results, you need to modify your query as follows:

insert into prices (group, id, price)
select 
    7, articleId, 1.50
from article where name like 'ABC%';

In this modified query:

  • The constant fields ("group" and "price") are specified directly in the VALUES clause.
  • The subquery retrieves the "articleId" values from the "article" table using the LIKE condition.
  • The selected values are inserted into the specified columns in the "prices" table.

The above is the detailed content of How to Insert Multiple Rows into a Table Using a Subquery 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