SQL查询 - 仅在另一个条件下在WHERE中添加条件

Jak*_*net 0 sql where-clause

我想在where子句中做这样的事情

WHERE ( i.accountid = @accountid 
      AND CASE WHEN @IsTest IS NOT NULL THEN b.IsTest = @IsTest ELSE 1 = 1
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案不起作用.对此有什么解决方案吗?基本上我想根据@IsTest价值添加验证.

Lua*_*aan 5

您想使用简单的布尔逻辑:

where  
 i.accountid = @accountid
  and 
 (@IsTest is null or b.IsTest = @Istest)
Run Code Online (Sandbox Code Playgroud)

如果你想让你的case解决方案工作(仅仅是为了说明目的 - 这不是一个好主意),你需要让case返回一个你要比较的值--T-SQL实际上没有"bool"输入"(bit只是令人难以置信的小整数,它没有特殊的语法):

... and (case when @IsTest is not null then @IsTest else 1 end) = 1
Run Code Online (Sandbox Code Playgroud)