且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 WHERE 子句中应用条件过滤

更新时间:2022-01-25 19:09:09

你可以像这样使用 CASE 表达式:

You can use a CASE expressions like this:

案例示例

WHERE
    CASE 
        WHEN @Jobid > 0 THEN @Jobid     -- When @Jobid supplied use it.
        ELSE J.id                       -- When not; return current value.
    END = J.id

当@Jiobid 超过 0 时,它会与 J.id 进行比较.如果不将 J.id 与自身进行比较,这当然总是会导致匹配.

When @Jiobid exceeds 0 it is compared to J.id. When not J.id is compared to itself, which will of course always result in a match.

我个人更喜欢@jarlh 在上面的评论中建议的方法.简单性使代码更易于遵循.

Personally I prefer the approach suggested by @jarlh in the comments above. The simplicity makes the code easier to follow.

@jarlh 示例

WHERE
    (J.Id = @Jobid or @Jobid=0)

如果这些方法不能提高您的性能,请尝试将您的架构和一些示例记录添加到问题中.您也可以考虑发布执行计划.

If these approaches don't improve your performance try adding your schema and some sample records to the question. You might also consider posting the execution plan.