SQL Server 性能调优杂记(三)
2008-12-08 10:15:18 来源:WEB开发网这个例子和上面一个例子结果相反。
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文,至少你可以用临时表来获得优化。
- ››SQL Server 2008 R2 下如何清理数据库日志文件
- ››sqlite 存取中文的解决方法
- ››SQL2005、2008、2000 清空删除日志
- ››SQL Server 2005和SQL Server 2000数据的相互导入...
- ››sql server 2008 在安装了活动目录以后无法启动服...
- ››sqlserver 每30分自动生成一次
- ››sqlite 数据库 对 BOOL型 数据的插入处理正确用法...
- ››sql server自动生成批量执行SQL脚本的批处理
- ››sql server 2008亿万数据性能优化
- ››SQL Server 2008清空数据库日志方法
- ››sqlserver安装和简单的使用
- ››SQL Sever 2008 R2 数据库管理
更多精彩
赞助商链接