程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> SQL Server 性能調優雜記(三)

SQL Server 性能調優雜記(三)

編輯:關於SqlServer

  這個例子和上面一個例子結果相反。

  SQL文1

declare @CWB_NO varchar(50)
set @cwb_no='31301379874'
SELECT   a.AWB_NO,
  a.BWB_NO,
  a.CWB_NO,
  a.ORIGIN,
  a.DEST,
  a.MODIFY_ON,
  a.CREATED_ON,
  a.CONSIGNOR_CUSTOMER_CODE,
  a.CONSIGNOR_CODE, 
  a.CONSIGNOR_NAME,
  a.CONSIGNEE_NAME,
  a.CWB_STATUS,
  a.CWB_TYPE,
  ISNULL(a.PCS, 0) AS PCS,
  a.BWBLIST,
  b.PWEIGHT  
FROM    TB_CWB AS a
LEFT JOIN  TB_CWBWEIGHT AS b
ON a.CWB_NO = b.CWB_NO
AND b.AVAILABLE = 'Y' 
WHERE    a.AVAILABLE = 'Y'
AND (a.CWB_NO = @CWB_NO OR
                                     (( @CWB_NO IS NULL)
AND (a.AWB_NO = NULL OR NULL IS NULL)
AND (a.BWB_NO = NULL OR NULL IS NULL)
AND (a.IE_TYPE = NULL OR NULL IS NULL)
AND (a.CREATED_ON >= NULL OR NULL IS NULL)
AND (a.CREATED_ON <= NULL OR NULL IS NULL)
AND (a.PAYMENT = NULL OR NULL IS NULL)
AND (a.ORIGIN = NULL OR NULL IS NULL)
AND (a.DEST = NULL OR NULL IS NULL)
AND (a.CONSIGNOR_CUSTOMER_CODE = NULL OR NULL IS NULL)
AND (a.CONSIGNOR_NAME LIKE '%' + NULL + '%' OR NULL IS NULL)
AND (a.CONSIGNEE_NAME LIKE '%' + NULL + '%' OR NULL IS NULL)
AND (a.CWB_TYPE = NULL OR NULL IS NULL)))

  SQL Server根據這句SQL文執行產生的計劃

  在這個計劃中,SQL Server更多考慮是2個大數據量表的情況,采納了分別按聚集索引獲取數據並采用並行處理過濾掉數據後,在進行連接,在並行處理的執行計劃。

  在只查找一條記錄的時候,缺不是最佳的。沒有采用2個表的外鍵,我認為是預編譯的SQL文,SQLServer是從查詢結果是大數據量的角度來選擇執行計劃。結果這句語句需要花費7秒到16秒。



  換一種寫法,SQL 2

SELECT   a.AWB_NO,
  a.BWB_NO,
  a.CWB_NO,
  a.ORIGIN,
  a.DEST,
  a.MODIFY_ON,
  a.CREATED_ON,
  a.CONSIGNOR_CUSTOMER_CODE,
  a.CONSIGNOR_CODE, 
  a.CONSIGNOR_NAME,
  a.CONSIGNEE_NAME,
  a.CWB_STATUS,
  a.CWB_TYPE,
  ISNULL(a.PCS, 0) AS PCS,
  a.BWBLIST,
  b.PWEIGHT  
FROM    TB_CWB AS a
LEFT JOIN  TB_CWBWEIGHT AS b
ON a.CWB_NO = b.CWB_NO
AND b.AVAILABLE = 'Y' 
WHERE    a.AVAILABLE = 'Y'
AND (a.CWB_NO = '31301379874' OR
                                     (( '31301379874' IS NULL)
AND (a.AWB_NO = NULL OR NULL IS NULL)
AND (a.BWB_NO = NULL OR NULL IS NULL)
AND (a.IE_TYPE = NULL OR NULL IS NULL)
AND (a.CREATED_ON >= NULL OR NULL IS NULL)
AND (a.CREATED_ON <= NULL OR NULL IS NULL)
AND (a.PAYMENT = NULL OR NULL IS NULL)
AND (a.ORIGIN = NULL OR NULL IS NULL)
AND (a.DEST = NULL OR NULL IS NULL)
AND (a.CONSIGNOR_CUSTOMER_CODE = NULL OR NULL IS NULL)
AND (a.CONSIGNOR_NAME LIKE '%' + NULL + '%' OR NULL IS NULL)
AND (a.CONSIGNEE_NAME LIKE '%' + NULL + '%' OR NULL IS NULL)
AND (a.CWB_TYPE = NULL OR NULL IS NULL)))

  這句SQL文的執行計劃如下

  SQL Server采用了比較好的執行計劃。因為涉及記錄只有一條。先通過外鍵找到TB_CWBWeight的記錄,然後過濾,再和聚集索引找到的TB_CWB表記錄做數據合並。實際執行時間1秒都不到。

  2者相差很大。

  感覺,如果是單條查找,SQL文2的寫法應該比較好,SQL Server選擇執行計劃不會失誤。而采用存儲過程寫法的時候,還是要考慮有可能失誤的情況。所以,一般存儲過程中不應該寫冗長的SQL文,而是竟可能拆解成更簡單的SQL文,至少你可以用臨時表來獲得優化。

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved