我有一个满足以下条件的SQL查询执行块。
在第一个查询中,我们将条件附加如下。
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
当前,我正在执行查询1,如果找到0条记录,那么我正在执行Query2
请建议我如何以最少的执行量实现这一目标。
答案 0 :(得分: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)
答案 1 :(得分:0)
如果只需要一行:
select top (1) m.*
from Mobile
where value between @minprice - 1000 and @maxprice and
column2 = @otherparam
order by value desc
为了提高性能,您希望在mobile(column2, value)
上建立索引。
注意:between
的操作数顺序非常重要。较小的值应该是第二个操作数,而较大的应该是最后一个。
答案 2 :(得分:0)
尝试使用临时表。临时加载查询1的结果。如果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