[英]Adding to WHERE clause conditions using CASE
I have a stored procedure that accepts an optional @ID param. 我有一个接受可选@ID参数的存储过程。 When the param is passed in, I want the WHERE statement to include something like id = @ID, otherwise, when @ID is null, I don't want it to be filtered.
传入参数时,我希望WHERE语句包含类似id = @ID的内容,否则,当@ID为null时,我不希望对其进行过滤。
For example: 例如:
@ID BIGINT = NULL
SELECT * from myTable
WHERE
CASE
WHEN @ID IS NOT NULL THEN mytable.id = @ID
END
I am running this in SQL server 2016 and it says bad syntax near mytable.id = @ID. 我在SQL Server 2016中运行它,它说mytable.id = @ID附近的语法错误。 Can CASE be used in this way or should I try a different SQL method for this?
可以通过这种方式使用CASE,还是应该为此尝试其他SQL方法?
The only other option I considered to accomplish this was by using IF conditions in my stored procedure, but that didn't seem possible either based on my searches. 我考虑完成此操作的唯一其他选择是在存储过程中使用IF条件,但根据我的搜索似乎也不可能。
CASE is an expression, not a statement. CASE是一个表达式,而不是一个语句。 It is not used to control flow like this and it will not work.
它不能像这样控制流量,它将无法工作。
Your logic would need to be something like this. 您的逻辑将需要像这样。
Where mytable.id = ISNULL(@ID, mytable.id)
I should caution you that this pattern can lead to some poor performance. 我应该警告您,这种模式可能会导致性能下降。 For a more detailed explanation and some other options you should check out this article.
有关更详细的解释和其他选项,请查看本文。 http://www.sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
http://www.sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
A bad-performance approach would be: 效果不佳的方法是:
WHERE ISNULL(@ID,mytable.id) = mytable.id
A better-performance approach would be: 一种性能更好的方法是:
if(@ID IS NULL)
select * from ... without the WHERE condition
else
do your query with the condition mytable.id = @ID
Or build the query dynamically in the stored proc and execute it through sp_executesql
passing parameters 或者在存储的proc中动态构建查询,并通过
sp_executesql
传递参数来执行查询
Note: If the table is small enough, stick to simplicity and use the first option. 注意:如果表格足够小,请保持简洁并使用第一个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.