WEB开发网
开发学院数据库MSSQL Server SQL Server 性能调优杂记(三) 阅读

SQL Server 性能调优杂记(三)

 2008-12-08 10:15:18 来源:WEB开发网   
核心提示:这个例子和上面一个例子结果相反,SQL文1declare @CWB_NO varchar(50)set @cwb_no='31301379874'SELECTa.AWB_NO,a.BWB_NO,a.CWB_NO,a.ORIGIN,a.DEST,a.MODIFY_ON,a.CREATED_ON,a.CON

这个例子和上面一个例子结果相反。

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 性能调优杂记(三)

在这个计划中,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 性能调优杂记(三)

SQL Server采用了比较好的执行计划。因为涉及记录只有一条。先通过外键找到TB_CWBWeight的记录,然后过滤,再和聚集索引找到的TB_CWB表记录做数据合并。实际执行时间1秒都不到。

2者相差很大。

感觉,如果是单条查找,SQL文2的写法应该比较好,SQL Server选择执行计划不会失误。而采用存储过程写法的时候,还是要考虑有可能失误的情况。所以,一般存储过程中不应该写冗长的SQL文,而是竟可能拆解成更简单的SQL文,至少你可以用临时表来获得优化。

Tags:SQL Server 性能

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接