2016-08-11 135 views
2

我遇到了一個子查詢問題,希望有人可以幫助我。SQL子查詢超過1個值

如果我運行以下命令:

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和他們編譯不顯示這顯然是錯誤的消息計數不工作。

這是可能的還是我吠叫錯了樹?

非常感謝。

+1

如何只增加一個'where'子句來查詢? –

回答

1

因爲如果有這樣的行檢查,你可以使用EXISTS

IF EXISTS (SELECT ...) 

在你的情況我會做出選擇distinct返回一個特定的值只有一次:

select DISTINCT t4.code from OITM T0 ... 

UPDATE

由於@gordon-linoff指出,你可以過濾出th Ë不需要的值是這樣的:

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 
+0

感謝您的幫助。你能幫我按照EXISTS的語法嗎?當我使用IF EXISTS(...) – coblenski

+1

唉,它給NOT IN語法錯誤,也許這是@ gordon-linoff的意思。這是如何使子查詢正常運行:'SELECT T4.Code ... WHERE T2.DocEntry ='7060'AND T4.code NOT IN('22030010','22030001','22030009')'。添加更新到帖子。 –

+0

我不認爲這有效。它編譯但不顯示消息。 – coblenski

相關問題