在 SQL Server 2008 中执行视图时出现“超时已过期”错误

Posted

技术标签:

【中文标题】在 SQL Server 2008 中执行视图时出现“超时已过期”错误【英文标题】:"Timeout expired" error, when executing view in SQL Server 2008 【发布时间】:2012-03-08 05:25:22 【问题描述】:

我在 SQL Server 2008 中编写了一个查询。执行该查询大约需要 4 分钟。 我需要这个查询作为View。因此,我使用此查询创建了一个视图,当我尝试执行视图创建脚本时,它显示以下错误:

超时。 在操作完成之前超时时间已过或服务器没有响应。

查询是:

SELECT t.jrnno,
       (SELECT SUM(t1.amount)
          FROM dbo.T_sh AS t1
         WHERE (t1.b_or_s = '1') AND (t1.jrnno = t.jrnno)) AS buy,
       (SELECT SUM(t2.amount)
          FROM dbo.T_sh AS t2
         WHERE (t2.b_or_s = '2') AND (t2.jrnno = t.jrnno)) AS sale, 
       SUM(t.amount) AS Total, 
       SUM(t.h_crg) AS Howla, 
       SUM(t.l_crg) AS Laga, 
       SUM(t.taxamt) AS Tax, 
       SUM(t.commsn) AS Commission
  FROM dbo.T_sh AS t
 WHERE (t.tran_type = 'S')  
   AND (t.jrnno NOT IN (SELECT DISTINCT jrnno
                          FROM dbo.T_ledger))
GROUP BY t.jrnno

T_shT_ledger 两个表都有大约 100K 行。可能的原因是什么?我该如何克服?

更新:

select 
   t.jrnno, 
   SUM(CASE WHEN t.b_or_s = 1 THEN t.amount ELSE NULL END) buy,
   SUM(CASE WHEN t.b_or_s = 2 THEN t.amount ELSE NULL END) sale,
   SUM(t.amount) AS Total, 
   SUM(t.h_crg) AS Howla, 
   SUM(t.l_crg) AS Laga, 
   SUM(t.taxamt) AS Tax, 
   SUM(t.commsn) AS Commission
FROM 
   dbo.t_sh t
WHERE  
   t.tran_type = 'S'
   AND NOT EXISTS(SELECT 1 FROM  dbo.T_ledger x where x.jrnno = t.jrnno)
group by 
   t.jrnno

它解决了我的问题。感谢大家的快速回复。

【问题讨论】:

【参考方案1】:

试试这个查询:

select 
t.jrno, 
SUM(CASE WHEN t1.b_or_s = 1 THEN t.amount ELSE NULL END) buy,
SUM(CASE WHEN t1.b_or_s = 2 THEN t.amount ELSE NULL END) sale,
SUM(t.amount) AS Total, 
SUM(t.h_crg) AS Howla, 
SUM(t.l_crg) AS Laga, 
SUM(t.taxamt) AS Tax, 
SUM(t.commsn) AS Commission
FROM dbo.t_sh t
WHERE  t.tran_type = 'S'
AND NOT EXISTS(SELECT 1 FROM  dbo.T_ledger x x.jrno = t.jrno)

【讨论】:

太棒了。它像魔术一样工作。执行需要 2 秒。之前没有使用“不存在”。谢谢。【参考方案2】:

您的查询只需扫描dbo.T_sh一次:

  SELECT t.jrnno,
         SUM(CASE WHEN t.b_or_s = 1 THEN t.amount ELSE NULL END) AS buy,
         SUM(CASE WHEN t.b_or_s = 2 THEN t.amount ELSE NULL END) AS sale,
         SUM(t.amount) AS Total, 
         SUM(t.h_crg) AS Howla, 
         SUM(t.l_crg) AS Laga, 
         SUM(t.taxamt) AS Tax, 
         SUM(t.commsn) AS Commission
    FROM dbo.T_sh AS t
   WHERE t.tran_type = 'S'
     AND t.jrnno NOT IN (SELECT DISTINCT 
                                tl.jrnno
                           FROM dbo.T_ledger tl)
GROUP BY t.jrnno

【讨论】:

以上是关于在 SQL Server 2008 中执行视图时出现“超时已过期”错误的主要内容,如果未能解决你的问题,请参考以下文章

SP 执行时 SQL Server 2008 中的 QUOTED IDENTIFIER 错误

sql server 2008 在与 SQL Server 提示建立连接时出现与网络相关的或特定于实例的错误

SQL Server 2008 R2 和索引视图中的执行计划

sql server 2008安装试图执行未经授权的操作

sql server 2008安装出错,试图执行未经授权的操作。

sql server 2008安装出错,试图执行未经授权的操作。