Home > Database > Mysql Tutorial > How to Fix 'Subquery Returned More Than 1 Value' Error in SQL Server?

How to Fix 'Subquery Returned More Than 1 Value' Error in SQL Server?

Patricia Arquette
Release: 2025-01-17 15:02:10
Original
559 people have browsed it

How to Fix

Solving the problem of subquery returning multiple values ​​in SQL Server

When executing the following query:

<code class="language-sql">SELECT 
   orderdetails.sku,
   orderdetails.mf_item_number,
   orderdetails.qty,
   orderdetails.price,
   supplier.supplierid,
   supplier.suppliername,
   supplier.dropshipfees,
   cost = (SELECT supplier_item.price
           FROM   supplier_item,
                  orderdetails,
                  supplier
           WHERE  supplier_item.sku = orderdetails.sku
                  AND supplier_item.supplierid = supplier.supplierid)
FROM   orderdetails,
       supplier,
       group_master
WHERE  invoiceid = '339740'
       AND orderdetails.mfr_id = supplier.supplierid
       AND group_master.sku = orderdetails.sku  </code>
Copy after login

will encounter the following error:

<code>Msg 512, Level 16, State 1, Line 2
子查询返回多个值。当子查询位于 =、!=、<、<=、>、>= 之后,或者用作表达式时,这是不允许的。</code>
Copy after login

This error occurs because the subquery used in the cost expression returns multiple values, which is not allowed when comparing using the equals operator (=). To fix this, replace the subquery with a join operation that explicitly selects individual values ​​of the cost column:

<code class="language-sql">SELECT
    od.Sku,
    od.mf_item_number,
    od.Qty,
    od.Price,
    s.SupplierId,
    s.SupplierName,
    s.DropShipFees,
    si.Price as cost
FROM
    OrderDetails od
    INNER JOIN Supplier s on s.SupplierId = od.Mfr_ID
    INNER JOIN Group_Master gm on gm.Sku = od.Sku
    INNER JOIN Supplier_Item si on si.SKU = od.Sku and si.SupplierId = s.SupplierID
WHERE
    od.invoiceid = '339740'</code>
Copy after login

This query will now return a single value for the cost column, thus resolving the subquery error.

The above is the detailed content of How to Fix 'Subquery Returned More Than 1 Value' Error 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