SQL Server DELETE错误 - 子查询返回的值超过1

时间:2011-06-19 21:00:22

标签: sql sql-server

尝试使用子查询删除行时出错:

DELETE FROM tblOrderDetails
WHERE  ProductID = (SELECT ProductID FROM tblProducts WHERE Discontinued = 1)

我理解的错误是:

  

Msg 512,Level 16,State 1,Line 1
  子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
  声明已经终止。

我知道子查询返回了几个值,但是如何删除这些行 谢谢任何帮助将不胜感激。 帕特里克

5 个答案:

答案 0 :(得分:9)

试试这个

DELETE FROM tblOrderDetails 
WHERE ProductID IN (
    SELECT ProductID 
    FROM tblProducts 
    WHERE Discontinued = 1
)

答案 1 :(得分:2)

使用in

DELETE FROM tblOrderDetails WHERE ProductID IN (SELECT ProductID FROM tblProducts WHERE Discontinued = 1)

答案 2 :(得分:2)

试试这个:

 DELETE OD
 FROM tblOrderDetails AS OD
 INNER JOIN tblProducts as P ON P.ProductID =OD.ProductID 
 WHERE P.Discontinued = 1; 

答案 3 :(得分:1)

IN将允许您定义应删除的集合而不是单行。

DELETE FROM tblOrderDetails WHERE ProductID IN (SELECT ProductID FROM tblProducts WHERE Discontinued = 1)

答案 4 :(得分:1)

DELETE 
  FROM tblOrderDetails
 WHERE EXISTS (
               SELECT * 
                 FROM tblProducts AS T2
                WHERE T2.ProductID = tblOrderDetails.ProductID
                      AND T2.Discontinued = 1
              );

但审计师对现已停产的产品的历史数据丢失有何看法......?