2012-03-08 102 views
5

我在SQL Server 2008中編寫了一個查詢。查詢大約需要4分鐘才能執行。
我需要此查詢作爲View。所以,我創建了一個視圖與此查詢,當我嘗試執行視圖創建腳本,它顯示了以下錯誤:在SQL Server 2008中執行視圖時出現「Timeout expired」錯誤

Timeout Expired.
The timeout period elapsed prior to completion of the operation or the server is not responding.

查詢是:

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 

它解決了我的問題。感謝大家的快速回復。

回答

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) 
+0

很好。它像魔術一樣工作。花了2秒執行。之前沒有使用'NOT EXISTS'。謝謝。 – 2012-03-08 05:50:00

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 
+0

很大。但是,仍然表現出同樣的問題。謝謝。 – 2012-03-08 05:45:29