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

时间:2012-03-08 05:25:23

标签: sql sql-server sql-server-2008 query-optimization

我在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

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

2 个答案:

答案 0 :(得分:4)

尝试此查询:

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)

答案 1 :(得分: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