1

我有一个查询:

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

4

3 回答 3

3

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
于 2011-01-28T06:48:30.343 回答
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

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

这可能是因为查询执行了两次并且它包含一个子查询。在执行这样的查询时不知道里面到底发生了什么。但是像这样更改查询解决了我延迟的问题

于 2011-01-28T06:44:57.640 回答
0

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

如果“12”实际上是一个参数,那么您可能是参数嗅探的受害者。 这是一个带有一些有用答案的问题

提到但未解释的一种解决方案是屏蔽参数 - 通过声明一个局部变量来做到这一点,将其设置为参数的值并在查询中使用它。

于 2011-01-28T08:45:21.250 回答