加入收藏 | 设为首页 | 会员中心 | 我要投稿 南京站长网 (https://www.025zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 如果在CTE中?

发布时间:2021-03-06 04:18:17 所属栏目:MsSql教程 来源:网络整理
导读:我想基于一个编码在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中有其他可能吗?如

我想基于一个编码在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,则可以使用其他技术,请参阅:Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later)

如果您使用的是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上定义了一个索引)

(编辑:南京站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读