sql-server – 如果在CTE中?

前端之家收集整理的这篇文章主要介绍了sql-server – 如果在CTE中?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想基于一个编码在CTE中执行select语句.类似下面的东西
  1. ;with CTE_AorB
  2. (
  3. if(condition)
  4. select * from table_A
  5. else
  6. select * from table_B
  7. ),CTE_C as
  8. (
  9. select * from CTE_AorB // processing is removed
  10. )

但是我得到了错误.如果在CTE中有其他可能吗?如果没有,是否有解决方案或更好的方法.

谢谢.

解决方法

尝试:
  1. ;with CTE_AorB
  2. (
  3. select * from table_A WHERE (condition true)
  4. union all
  5. select * from table_B WHERE NOT (condition true)
  6. ),CTE_C as
  7. (
  8. select * from CTE_AorB // processing is removed
  9. )

具有动态搜索条件的键是确保使用索引,这是一篇关于如何处理此主题的非常全面的文章

Dynamic Search Conditions in T-SQL by Erland Sommarskog

它涵盖了尝试使用多个可选搜索条件编写查询的所有问题和方法.您需要关注的主要问题不是代码的重复,而是索引的使用.如果您的查询无法使用索引,它将执行不良.可以使用几种技术,这些技术可能允许也可能不允许使用索引.

这是目录:

  1. Introduction
  2. The Case Study: Searching Orders
  3. The Northgale Database
  4. Dynamic sql
  5. Introduction
  6. Using sp_executesql
  7. Using the CLR
  8. Using EXEC()
  9. When Caching Is Not Really What You Want
  10. Static sql
  11. Introduction
  12. x = @x OR @x IS NULL
  13. Using IF statements
  14. Umachandar's Bag of Tricks
  15. Using Temp Tables
  16. x = @x AND @x IS NOT NULL
  17. Handling Complex Conditions
  18. Hybrid Solutions – Using both Static and Dynamic sql
  19. Using Views
  20. Using Inline Table Functions
  21. Conclusion
  22. Feedback and Acknowledgements
  23. Revision History

如果您使用的是适当版本的sql Server 2008,则可以使用其他技术,请参阅:@L_502_1@

如果您使用的是sql Server 2008的正确版本,则只需向查询添加OPTION(RECOMPILE),并在运行时将局部变量的值用于优化.

考虑到这一点,OPTION(RECOMPILE)将采用此代码(其中没有索引可用于此混乱的OR):

  1. WHERE
  2. (@search1 IS NULL or Column1=@Search1)
  3. AND (@search2 IS NULL or Column2=@Search2)
  4. AND (@search3 IS NULL or Column3=@Search3)

并在运行时优化它(假设只有@ Search2传入一个值):

  1. WHERE
  2. Column2=@Search2

并且可以使用索引(如果在Column2上定义了一个索引)

猜你在找的MsSQL相关文章