You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CASE/WHEN在WHERE子句中实现基于变量的条件查询?

解决方案

当然可以把三种查询逻辑整合到单条SELECT语句的WHERE子句中,下面提供几种简洁的实现方式:

方法1:直接用逻辑条件组合

这种写法最直观,直接把分支逻辑转换成WHERE里的布尔条件:

declare @cucu varchar(10)
select @cucu = 'c'

create table #t(id int, title varchar(50), p bit)
insert into #t(id, title, p) values (1, 'alpha', 0)
insert into #t(id, title, p) values (2, 'beta', 1)
insert into #t(id, title, p) values (3, 'gamma', 0)

-- 整合后的查询
select  *
from    #t
where   
    (@cucu = 'a' and p = 0)
    or (@cucu = 'b' and p = 1)
    or (@cucu not in ('a', 'b'))

drop table #t

方法2:使用CASE表达式

利用CASE返回匹配的p值,当@cucu为其他值时,让CASE返回p本身(等价于p=p,恒成立):

select  *
from    #t
where   
    p = case 
        when @cucu = 'a' then 0
        when @cucu = 'b' then 1
        else p -- 匹配所有行
    end

或者另一种CASE写法,直接返回布尔判断结果:

select  *
from    #t
where   
    case 
        when @cucu = 'a' then (p = 0)
        when @cucu = 'b' then (p = 1)
        else 1 -- 1代表逻辑真,选中所有行
    end = 1

改进你之前的变量方法

如果你想保留用变量的思路,可以把@b设为NULL来处理第三种情况,通过OR @b IS NULL匹配所有行:

declare @cucu varchar(10)
select @cucu = 'c'

create table #t(id int, title varchar(50), p bit)
insert into #t(id, title, p) values (1, 'alpha', 0)
insert into #t(id, title, p) values (2, 'beta', 1)
insert into #t(id, title, p) values (3, 'gamma', 0)

declare @b bit;
select @b = case 
    when @cucu = 'a' then 0
    when @cucu = 'b' then 1
    else null -- 非a/b时设为NULL
end

select  *
from    #t
where   p = @b OR @b IS NULL

drop table #t

内容的提问来源于stack exchange,提问作者Ash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:06:19