我想使用變量來表示將在查詢的WHERE子句中使用的結果集。將子查詢設置爲要在IN運算符內使用的變量
SELECT *
FROM Table1
WHERE
Exam1_ID IN (SELECT Id FROM Exam)
OR Exam2_ID IN (SELECT Id FROM Exam)
OR Exam3_ID IN (SELECT Id FROM Exam)
OR Exam4_ID IN (SELECT Id FROM Exam)
我想用一個變量代替SELECT Id FROM Exam
,所以我不必重複查詢。我試過聲明一個變量,但由於子查詢的結果可能包含多個整數,所以我不確定將變量聲明爲什麼。我繼續嘗試...
DECLARE @SubQuery INT;
SET @SubQuery = (SELECT Id FROM Exam);
SELECT *
FROM Table1
WHERE
Exam1_ID IN (@SubQuery)
OR Exam2_ID IN (@SubQuery)
OR Exam3_ID IN (@SubQuery)
OR Exam4_ID IN (@SubQuery)
我收到以下錯誤..
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
您是否嘗試將該變量聲明爲表而不是單個值? –
您將您的變量聲明爲INT,這就是它的* an *(單數)int,因此它不能保存多個值。要做你想做的事情,你可以將這些值連接成一個'varchar',並使用動態sql(儘管有更簡單的解決方案,就像Rich Benner的解決方案)。 – HoneyBadger