同一查询的执行时间不同 - SQL Server

我有一个问题:
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     
已邀请:
EXISTS会为您短路IF
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
    
试试这个
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
我也有同样的情况,并解决了这样的问题。 这可能是因为查询正在执行两次并且它包含一个子查询。在执行像这样的查询时,不知道究竟发生了什么。但改变这样的查询解决了我的延迟问题     
mainid值是否实际上是硬编码的(12),或者这仅仅是示例,实际上,您将此值作为参数传递给存储过程? (如果是硬编码,您可能希望忽略以下内容)。 如果“12”实际上是一个参数,您可能是参数嗅探的受害者。这是一个有一些有用答案的问题。 提到但未解释的一个解决方案是屏蔽参数 - 通过声明局部变量,将其设置为参数值并在查询中使用它来执行此操作。     

要回复问题请先登录注册