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
Patricia ArquetteOriginal
2025-01-17 15:02:10561browse

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>

will encounter the following error:

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

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>

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!

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