【问题标题】:Dynamically select a version of WHERE clause in SQL SELECT statement?在 SQL SELECT 语句中动态选择 WHERE 子句的版本?
【发布时间】:2015-10-27 17:02:31
【问题描述】:

基本上,我想在我的 SQL SELECT 语句中选择 WHERE 子句的两个版本之一,而不必复制整个 SELECT 语句的两个版本。

例如,我想指定一个变量,如@topclients, 并在@topclients = 'true' 时执行以下WHERE 子句:

WHERE 
    CAST(event_dtm AS DATE) between @start and @end
    and client IN ('client1','client2', 'client3')

或者当@topclients = 'false'时执行下面的WHERE子句:

WHERE 
    CAST(event_dtm AS DATE) between @start and @end

我该怎么做?

【问题讨论】:

  • 仅供参考,您的CAST(event_dtm AS DATE) 阻止使用索引。这将导致表扫描,因此表中的行越多,运行所需的时间就越长。如果您只想让某些东西不管性能如何都能正常工作,请使用:WHERE CAST(event_dtm AS DATE) between @start and @end and (@topclients = 'false' OR client IN ('client1','client2', 'client3')) 您可以尝试在查询末尾添加OPTION (RECOMPILE),这可能有助于提高性能。

标签: sql-server


【解决方案1】:

只需使用:

WHERE 
    CAST(event_dtm AS DATE) between @start and @end
    and (
      client IN ('client1','client2', 'client3') 
      or @topclients = 'false'
    )

【讨论】:

  • 对不起,这没有做到。无论哪种方式,此查询都会返回所有客户端的数据(不仅仅是 3 个)
  • 如果@topclients 不是'false',这将只返回这3 个数据
猜你喜欢
  • 2013-06-14
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
相关资源
最近更新 更多