大于SQL CASE语句

IIS*_*ite 16 sql sql-server

我很难找到比SQL语句更大的内容.

这是我的代码:

select one, two three from orders
where case when @orderid > 0 then orders.orderid = @orderid end
Run Code Online (Sandbox Code Playgroud)

@orderid是传递给存储过程的参数.我们的想法是,如果一个有效的(> 0)的OrderID传递,然后使用它作为在where子句中的过滤器,否则不要使用它.

NYC*_*Net 20

Guffa有正确的答案,但你使用CASE技巧(偶尔派上用场)的方式就是:

--If order ID is greater than 0, use it for selection
--otherwise return all of the orders.
select one, two, three
from orders
where orders.orderid = CASE
    WHEN @orderid > 0 then @orderid
    ELSE orders.orderid
END
Run Code Online (Sandbox Code Playgroud)

CASE总是必须返回一些东西,所以如果你想有条件地"禁用"WHERE子句中的一个语句而不能使用OR,你可以设置等于它自己的东西,并且应该总是为真(除非比较空值) ).

编辑:我还应该说,对于这样的查询,其中可以返回的行数可能会有很大差异(一行对整个表),使用OPTION(RECOMPILE)提示可能有助于单行案例中的性能.

  • +1 用于案例解决方案,并指出它不适用于 NULL (2认同)