【问题标题】:Execute another block if no records found in block 1如果在块 1 中没有找到记录,则执行另一个块
【发布时间】:2019-07-03 10:13:19
【问题描述】:

我有一个具有以下条件的 SQL 查询执行块。

在第一个查询中,我们附加 where 条件,如下所示。

Declare  @maxprice int 
Declare  @minprice int 

查询 1

Select * FROM Mobiles where value between @maxprice and @minprice and column2= @otherparam 

如果在上述查询中没有找到记录,那么我想在查询 2 中进行一些修改来执行查询。

查询 2

Select * FROM Mobiles where value between @maxprice - 1000 and @minprice - 1000 and column2= @otherparam 

根据上述条件,如果在特定日期范围内找不到移动设备,那么我想将最大和最小金额降低 1000 RS。

即@maxprice = 10000 & @minprice = 8000 如果没有找到上述记录,那么我想修改参数并再次执行查询,

SET @maxprice = 9000
SET @minprice = 7000 

目前我正在执行 Query 1,如果找到 0 条记录,那么我正在执行 Query2

请建议我如何以最少的执行来实现这一目标。

【问题讨论】:

    标签: sql sql-server tsql union where-clause


    【解决方案1】:

    第一个查询可以使用 CTE,第二个查询可以使用 UNION ALL:

    with cte as (
      Select * FROM Mobiles 
      where value between @maxprice and @minprice and column2= @otherparam 
    )
    Select * from cte
    union all
    Select * FROM Mobiles 
    where value between @maxprice - 1000 and @minprice - 1000 and column2= @otherparam 
          and not exists (select 1 from cte) 
    

    【讨论】:

      【解决方案2】:

      如果你只想要一行:

      select top (1) m.* 
      from Mobile
      where value between @minprice - 1000 and @maxprice and
            column2 = @otherparam 
      order by value desc
      

      为了提高性能,您需要在mobile(column2, value) 上建立索引。

      注意:between 的操作数顺序非常重要。第二个操作数应该越小,最后一个操作数越大。

      【讨论】:

      • @minprice - 1000 存储在变量中不是更好吗?
      • @lakta 。 . .问 OP。这是在回答他/她提出的问题。
      • 我问的是一般性能问题。据我所知,最好在变量中进行计算,而不是为每一行重新计算它
      • @lakta 。 . .该值应在编译阶段进行评估。即便如此,将两个数字相加在性能方面可能无法检测到。
      【解决方案3】:

      尝试使用临时表。在 temp 中加载查询 1 的结果。如果 temp 没有数据,则在 temp 中加载查询 2 的结果。显示来自 temp 的数据

      Declare  @maxprice int 
      Declare  @minprice int 
      create table #tmpMobiles (/*... your structue of data*/)
      
      insert into #tmpMobiles
      Select * FROM Mobiles where value between @maxprice and @minprice and column2= @otherparam 
      
      if not exists(select top 1 * from #tmpMobiles) begin
          set @maxprice = @maxprice - 1000
          set @minprice = @minprice - 1000
      
          insert into #tmpMobiles
          Select * FROM Mobiles where value between @maxprice and @minprice and column2= @otherparam 
      end
      
      select * from #tmpMobiles
      

      【讨论】:

        猜你喜欢
        • 2011-12-27
        • 2017-07-17
        • 1970-01-01
        • 2012-08-10
        • 2013-08-21
        • 2013-07-24
        • 1970-01-01
        • 2010-12-11
        • 2020-08-17
        相关资源
        最近更新 更多