我正在尝试使用由输入参数确定的 WHERE
子句构建 T-SQL 语句。像这样的东西:
SELECT * FROM table
WHERE id IN
CASE WHEN @param THEN
(1,2,4,5,8)
ELSE
(9,7,3)
END
我已经尝试了所有我能想到的移动 IN、CASE 等的组合。这(或类似的东西)可能吗?
最佳答案
试试这个:
SELECT * FROM table
WHERE (@param='??' AND id IN (1,2,4,5,8))
OR (@param!='??' AND id in (9,7,3))
这会在使用索引时出现问题。
动态搜索条件的关键是确保使用索引,而不是如何轻松地重用代码、消除查询中的重复或尝试使用相同的查询来完成所有事情。这是一篇关于如何处理这个主题的非常全面的文章:
Dynamic Search Conditions in T-SQL by Erland Sommarskog
它涵盖了尝试编写具有多个可选搜索条件的查询的所有问题和方法。您需要关注的主要事情不是代码重复,而是索引的使用。如果您的查询未能使用索引,它将表现不佳。可以使用多种技术,这些技术可能允许也可能不允许使用索引。
这是目录:
Introduction The Case Study: Searching Orders The Northgale Database Dynamic SQL Introduction Using sp_executesql Using the CLR Using EXEC() When Caching Is Not Really What You Want Static SQL Introduction x = @x OR @x IS NULL Using IF statements Umachandar's Bag of Tricks Using Temp Tables x = @x AND @x IS NOT NULL Handling Complex Conditions Hybrid Solutions – Using both Static and Dynamic SQL Using Views Using Inline Table Functions Conclusion Feedback and Acknowledgements Revision History
if you are on the proper version of SQL Server 2008, there is an additional technique that can be used, see: Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later)
If you are on that proper release of SQL Server 2008, you can just add OPTION (RECOMPILE)
to the query and the local variable's value at run time is used for the optimizations.
Consider this, OPTION (RECOMPILE)
will take this code (where no index can be used with this mess of OR
s):
WHERE
(@search1 IS NULL or Column1=@Search1)
AND (@search2 IS NULL or Column2=@Search2)
AND (@search3 IS NULL or Column3=@Search3)
并在运行时将其优化为(前提是只有@Search2 传入了一个值):
WHERE
Column2=@Search2
并且可以使用一个索引(如果你在 Column2 上定义了一个)
关于tsql - 是否可以将 CASE 与 IN 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2924320/