前提:以前作一个项目,要求统计销售库存,若是库存表月末最后一天没有数据,就往前循环五天,例:学习
如当前查询3月31号库存数据,该数据表31号没有数据,数据就取29号,当前思路查询是用while 循环,若是没有数据往前循环5天,一直到取到数据为止。优化
如图:spa
但是当数据量大的时候,用循环的话会使数据查询变量,并且效率也不高,速度也很慢code
代码优化改进:blog
update HBZY_SaleAreaTemp set --storemount=dbo.fn_HBZY_GetStoreMountLast(@saledate,productno,cityno), --被优化 用该语句和下面语句相差时间近10分钟 storemount=isnull((select top 1 g.storemount from hbzy_sale g where g.storemount is not null and g.productno=HBZY_SaleAreaTemp.productno and g.cityno=HBZY_SaleAreaTemp.cityno and datediff(Day,@saledate,g.saledate)>-4 and datediff(Day,@saledate,g.saledate)<=0 ),0) where datediff(D,saledate,@saledate)=0
联表查询,若是判断若是直接以日期为条件:以日期排序,取一条传入参很多天期内前5的数据,并且不能为空。这样的话一条Sql语句就能搞定,并且效率也比以前高出不少。排序
总结:在作项目的过程当中,重要的不是着急完成任务,而是先有思路,若是当前思路明确,再考虑代码的优化性,这样还能省不时间,固然这样的思路不是一天两天就能成形,还需本身在项目中多去总结不断学习,学习别人学代码的思想。总之,加油吧。。。ci