2011-01-28 136 views
1

我有一个查询:不同的执行时间相同的查询 - SQL服务器

Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 

当我执行这个查询,它正在采取1-2秒来执行,但是当我使用相同的查询存储过程,下面的查询花费5分钟以上:

If(Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12)) 
    BEGIN 
     -- CREATE TEMPORARY TABLE [Say: #temp1] 
#temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 
     drop #temp1 
    END 

这可能是什么原因?我该如何解决这个问题?我从asp.net运行SP

+0

为什么IF语句?你想做什么? – gbn 2011-01-28 06:32:02

+0

您是否检查过查询计划和io/cpu统计信息? – sisve 2011-01-28 07:27:10

+0

对于那些面临同样问题的人:两个答案[by:binil&by:gbn]都适合我。 – Zerotoinfinity 2011-01-28 08:49:05

回答

3

一个EXISTS意志短路如果你

If EXISTS (Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12)) 
    BEGIN 
     -- CREATE TEMPORARY TABLE [Say: #temp1] 
#temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 

    END 

但是,为什么不询问tbl_abc和tbl_xyz一次?

Select a 
    INTO #temp1 
    from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
    IF EXISTS (SELECT * FROM #temp1) /* or use @@ROWCOUNT*/ 
    BEGIN 
    --DoStuff 
    END 
    drop TABLE #temp1 
2

试试这个

declare @Count int 

select @Count = count (a) from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 

if(@Count > 0) 
begin 
    #temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 
     drop #temp1 
end 

我也有同样的情况,解决了这个样子。

这可能是因为执行查询时的两倍,它包含一个子查询。不知道在执行这样的查询时发生了什么。但改变这样的查询解决了我的得到延迟问题

0

mainid值是否实际硬编码(12),还是仅仅是示例,实际上,您将此值作为参数传递给您的存储过程? (如果它是硬编码的,你可能希望忽略以下内容)。

如果“12”是逸岸参数,你可能是参数嗅探的受害者。 Here's a question with some useful answers

一个方案中提到不可言传是掩盖参数 - 通过声明一个局部变量做到这一点,将其设置为您的参数值,并在查询中使用。

相关问题