Sql文的where中使用case when

来源:百度知道 编辑:UC知道 时间:2024/05/14 10:55:19
有这样一段sql文。
select B.bCol_1,B.bCol_2,C.cCol_1
from TBL_B B left join TBL_C C
on B.bCol_Key = C.cCol_Key
where B.bCol_Time < 'xxxx'

现在需要扩展功能,就是只有当表B.bCol_Flag=0时,where的条件改为C.cCol_Time < 'xxxx',其他的情况保持不变。不知道where里面能不能再用case when或者还有其他的,如果能用的话,怎么个写法。
因为这个是扩展功能,而且这段代码是在Procedure中的,所以不太能用参数和if…else控制来写。
比较急,如果代码通过,我会加满分的。谢谢。

这样就可以了
select B.bCol_1,B.bCol_2,C.cCol_1
from TBL_B B left join TBL_C C
on B.bCol_Key = C.cCol_Key
where (B.bCol_Time < 'xxxx' and B.bCol_Flag<>0) or ( C.cCol_Time < 'xxxx' and B.bCol_Flag=0)

declare @strsql varchar(8000)
set @strsql='select B.bCol_1,B.bCol_2,C.cCol_1
from TBL_B B left join TBL_C C
on B.bCol_Key = C.cCol_Key '
declare @bCol_Flag int
declare @xxxx varchar(8000)
set @xxxx='xxxx'
select @bCol_Flag=B.bCol_Flag from B
if(@bCol_Flag = 0)
begin
set @strsql = @strsql + 'where B.bCol_Time < '+ @xxxx
end
exec(@strsql)