我想基于一个编码在CTE中执行select语句.类似下面的东西
- ;with CTE_AorB
- (
- if(condition)
- select * from table_A
- else
- select * from table_B
- ),CTE_C as
- (
- select * from CTE_AorB // processing is removed
- )
但是我得到了错误.如果在CTE中有其他可能吗?如果没有,是否有解决方案或更好的方法.
谢谢.
解决方法
尝试:
- ;with CTE_AorB
- (
- select * from table_A WHERE (condition true)
- union all
- select * from table_B WHERE NOT (condition true)
- ),CTE_C as
- (
- select * from CTE_AorB // processing is removed
- )
具有动态搜索条件的键是确保使用索引,这是一篇关于如何处理此主题的非常全面的文章:
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
如果您使用的是适当版本的sql Server 2008,则可以使用其他技术,请参阅:@L_502_1@
如果您使用的是sql Server 2008的正确版本,则只需向查询添加OPTION(RECOMPILE),并在运行时将局部变量的值用于优化.
考虑到这一点,OPTION(RECOMPILE)将采用此代码(其中没有索引可用于此混乱的OR):
- 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上定义了一个索引)