【问题标题】:Different execution time for same query - SQL Server同一查询的不同执行时间 - SQL Server
【发布时间】:2011-01-28 06:23:58
【问题描述】:

我有一个问题:

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

【问题讨论】:

  • 为什么是 IF 语句?你想做什么?
  • 你检查过查询计划和 io/cpu 统计信息吗?
  • 对于那些面临同样问题的人:两个答案 [by: binil & by: gbn] 对我有用。

标签: asp.net sql-server sql-server-2005 executiontimeout


【解决方案1】:

一个 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

【讨论】:

    【解决方案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
    

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

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

    【讨论】:

    • 这虽然有效,但效率不高。根据我的回答和stackoverflow.com/questions/3271455/…,您将使用 EXISTS
    • @gbn 但是在使用“exists”时我发现了同样的问题。执行时间太长了。但是当我像上面的答案一样改变它时,它开始正常工作。我不知道为什么。
    • @gbn 当你在 sql server 中检查它存在时工作正常。但是从我的应用程序调用它时,它会延迟,有时会抛出异常。我的表包含超过 1000000 条记录
    【解决方案3】:

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

    如果“12”实际上是一个参数,那么您可能是参数嗅探的受害者。 Here's a question with some useful answers

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2011-03-05
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多