将 CASE 的多个结果分配给 WHERE col IN

Assigning multiple results from CASE to WHERE col IN

我在使用 case 时收到这条消息,我不想让表达式检查 id 是否为空,那将是不必要的额外代码。

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

declare @idchar(2)
set @id= ''

select names from Units
where id in(    
    case @id
        when '' then (select id from Units)
        else @id
    end
)

您可以按如下方式重写您的查询:

select names from Units
where (@id = '' AND id in(select id from Units)) OR id = @id

在这种情况下,如果 @id'',则评估条件 id in(select id from Units)。但是,如果 @id 有任何其他值,则评估条件 id = @id。这假设 @id 不能有值 NULL.

编辑: 查看查询后,查询似乎可以简化很多。您根本不需要 IN 部分,因为您正试图从同一个 table 访问所有记录,因此您可以使用更简单的查询:

select names from Units
where @id = '' OR id = @id

假设您永远不必处理空值,这样做就可以了:

SELECT names
 from Units
 where (id = @Id or (isnull(@Id, '') = ''))