前提:以前作一個項目,要求統計銷售庫存,若是庫存表月末最後一天沒有數據,就往前循環五天,例:學習
如當前查詢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