SQL子查询超过1个值

时间:2016-08-11 12:20:33

标签: sql subquery sql-server-2016

我遇到了子查询的问题,希望有人可以帮助我。

如果我运行以下内容:

select t4.code from OITM T0
 INNER JOIN DLN1 T1 ON T1.[ItemCode] = T0.[ItemCode]
 INNER JOIN ODLN T2 ON T2.[DocEntry] = T1.[DocEntry]
 INNER JOIN ITM10 T3 ON T3.[ItemCode] = T0.[ItemCode]
 LEFT JOIN ODCI T4 ON T4.[AbsEntry] = T3.[ISCommCode]
 WHERE T2.DocEntry = '7060'

结果是:

虽然在某些情况下可能会有多行符合所需的值,而其他行则不会同时发生。

我编写了一个查询,其中有一个子查询来检查这些结果,并在任何行中的[code]列不包含特定内容时显示一条消息:

IF(
(SELECT
    T4.Code
FROM OITM T0
 INNER JOIN DLN1 T1 ON T1.[ItemCode] = T0.[ItemCode]
 INNER JOIN ODLN T2 ON T2.[DocEntry] = T1.[DocEntry]
 INNER JOIN ITM10 T3 ON T3.[ItemCode] = T0.[ItemCode]
 LEFT JOIN ODCI T4 ON T4.[AbsEntry] = T3.[ISCommCode]
 WHERE T2.DocEntry = '7060') NOT IN ('22030010','22030001','22030009')
)
BEGIN
SELECT 'MESSAGE'
END

显然,如果必须返回多于1行,则无法编译:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

HAVING和COUNT不能正常编译而不显示明显错误的消息。

这是可能的还是我在错误的树上吠叫?

非常感谢。

1 个答案:

答案 0 :(得分:1)

要检查是否有这样的行,您可以使用EXISTS

IF EXISTS (SELECT ...)

在你的情况下,我会让select distinct只返回一次特定值:

select DISTINCT t4.code from OITM T0 ...

<强>更新

正如@gordon-linoff指出的那样,您可以过滤掉不需要的值,如下所示:

select distinct t4.code from OITM T0
...
where T2.DocEntry = '7060' and t4.code not in ('22030010','22030001','22030009')
-- using AND instead of ):  ^^^
-- so one ( will be enough between EXISTS and SELECT

把它放在一起:

IF EXISTS(SELECT ....  where T2.DocEntry = '7060' and t4.code not in ('22030010','22030001','22030009'))
BEGIN
    ...
END