sql Case语句带回多个值

时间:2013-10-30 15:51:49

标签: sql tsql

我想带回县Id和县名。如何解决此问题?

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.

3 个答案:

答案 0 :(得分:1)

您只能从CASE语句中返回一个表达式。请尝试使用IF / ELSE。

T-SQL中的CASE语句不是许多编程语言中的CASE / SWITCH等控制流语句。

答案 1 :(得分: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

答案 2 :(得分:0)

您的子查询返回了多个字段和可能的多个记录。像这样的子查询必须始终返回一个字段和一个记录。

我猜测INNER JOIN导致多条记录被返回。如果所有记录都具有相同的值,则可以DISTINCTTOP 1