2013-10-30 161 views
0

我想帶回縣名和縣名。我該如何解決這個問題?sql case語句帶回多個值

DECLARE @test int = 0; 


select 
CASE (@test) 
    when 0 then (SELECT co.Id, co.Description 
       FROM Dictionary.Counties as co 
       INNER JOIN CountyCollaboration as cc on cc.CountyId = co.Id 
       WHERE cc.CollaborationId = (SELECT cc1.CollaborationId from CountyCollaboration as cc1 
              WHERE cc1.CountyId = 34)) 
END 

我得到的錯誤only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

如果我註釋掉co.Description所以我只帶回co.Id,我得到一個不同的錯誤:subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >=, or when the subquery is used as as expression.

+1

如果你可以解釋你爲什麼要這樣做,可能會有一個簡單的解決方法,避免任何'CASE'或'IF'語句。 – bendataclear

回答

1

您只能從一個CASE返回一個表達式聲明。請嘗試使用IF/ELSE。

在許多編程語言中,T-SQL中的CASE語句不是像CASE/SWITCH這樣的控制流語句。

+1

事實上,在T-SQL中沒有'CASE'語句。有一個'CASE' *表達式*,與其他*表達式*共同計算一個值。 –

+0

這正是我想要的,謝謝菲爾。只要它讓我接受你的答案,我不得不再等幾分鐘。 – user1202606

1

我建議重構您的查詢看起來像這樣。

select id, country 
from 
(select co.id 
, co.country 
, case @test code for test goes here end caseresult 
from all that stuff you have as a subquery in your question 
) derivedtable 
0

你的子查詢中返回多個領域和可能的多記錄。像這樣的子查詢必須總是返回一個字段和一個記錄。

我猜INNER JOIN導致多個記錄被返回。如果所有記錄的值都相同,則可以輸入DISTINCTTOP 1