子查询在 Iif 条件下返回了超过 1 个值

Subquery returned more than 1 value with Iif conditions

select *
from employee
where controllingoffice in (
    Iif(1=1, (select id from controllingoffice), (select id from controllingoffice where OwnerId=4))
)

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

注意:两个子查询return多于1行

您的查询失败的原因是因为您的子查询 return 多个值,而 iif() 函数期望其参数的标量结果。因为 iif() 是一个函数,所以它求值为单个值而不是一组行。您不能像在过程语言中那样使用它来分支,因此您不能在这种意义上使子查询的执行成为条件。

下面的子查询允许您在一个地方表达一次驾驶条件。如果使用动态 SQL,那会很方便。我假设您的 1 = 1 是该输入的占位符。切换条件确定是所有行都是 returned 还是只有单个 OwnerId:

的行
select *
from employee
where controllingoffice in (
    select id from controllingoffice where
    <switch condition> or OwnerId = 4
);

顺便说一句,逻辑 X or (~X)Y 简化为 X or Y

您打算发生的情况的近似值如下所示:

select *
from employee
where
    1 = 1 and controllingoffice in (
        select id from controllingoffice
    )
 or 0 = 1 and controllingoffice in (
        select id from controllingoffice where OwnerId = 4
    );