简体   繁体   English

当@parm = -1返回IN时,否则返回@parm值

[英]When @parm =-1 return with IN, else return @parm value

I would like to filter my query but do know the syntax: 我想过滤查询,但是知道语法:

Here is my incorrect syntax: 这是我不正确的语法:

WHERE 
 (@StatusId = - 1 then Status.StatusId IN (1, 2, 3, 4)) 
else 
  Status.StatusId = @StatusId)
WHERE
(@StatusId = -1 AND Status.StatusID IN (1,2,3,4))
OR
(@StatusId <> -1 AND Status.StatusID = @StatusId)

Note that @StatusId <> -1 returns false if @StatusId is null. 请注意,如果@StatusId为null,则@StatusId <> -1返回false。 I'm assuming that the equality check should only happen if @StatusId does not equal -1. 我假设仅在@StatusId不等于-1时才进行相等性检查。 If that's not the case, then you can remove that part from the second clause. 如果不是这种情况,则可以从第二个子句中删除该部分。

You need to use Boolean logic. 您需要使用布尔逻辑。 Try this: 尝试这个:

WHERE 
 ((@StatusId = - 1 AND Status.StatusId IN (1, 2, 3, 4)) OR Status.StatusId = @StatusId)

Note that the whole statement is in parenthesis. 请注意,整个语句都用括号括起来。

You could do it like this, but it can cause query performance problems doing it this way (search for parameter sniffing). 您可以这样做,但是这样做可能会导致查询性能问题(搜索参数嗅探)。 Better would be to generate the correct SQL dynamically depending on the value of @StatusID and only run the bit you need. 更好的方法是根据@StatusID的值动态生成正确的SQL,然后仅运行所需的位。

Where (
  @StatusID = -1 And 
  Status.StatusID In (1, 2, 3, 4)
) Or (
  @StatusID != -1 And
  Status.StatusID = @StatusID
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM