Home > Database > Mysql Tutorial > How to Insert Multiple Rows into a SQL Server Table from a Non-Scalar Subquery?

How to Insert Multiple Rows into a SQL Server Table from a Non-Scalar Subquery?

Mary-Kate Olsen
Release: 2025-01-05 14:11:40
Original
686 people have browsed it

How to Insert Multiple Rows into a SQL Server Table from a Non-Scalar Subquery?

Inserting Values into a Table from a Non-Scalar Subquery

In SQL Server, inserting values into a table based on a subquery that returns multiple results can be challenging. Consider the following scenario:

You have two tables:

  • article
  • prices

You want to insert rows into the prices table with specific values for the group, id, and price columns, where the id values are derived from a subquery that selects matching IDs from the article table.

Incorrect Approach:

Trying to use a subquery with more than one result as the value for a column in an INSERT statement can result in an error, as demonstrated by the following incorrect SQL statement:

INSERT INTO prices (group, id, price) 
VALUES (7, (select articleId from article WHERE name LIKE 'ABC%'), 1.50);
Copy after login

Correct Solution:

To resolve this issue, use a SELECT statement to retrieve the desired values and insert them into the target table. Assign the constant values for the group and price columns directly within the SELECT statement:

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

In this statement, the subquery returns the article IDs matching the specified name criteria, and the constant values 7 and 1.50 are explicitly assigned to the group and price columns, respectively.

The above is the detailed content of How to Insert Multiple Rows into a SQL Server Table from a Non-Scalar Subquery?. 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