SQL Server中存儲過程比直接運行SQL語句慢的原因:
最近在BI項目中遇到一個問題,在直接sqlserver中直接 exec up_fact_d_gdsclass ‘2012-12-12’,執(zhí)行時間大概需要很長時間,大概20分鐘左右;但是在打開存儲過程取一句一句執(zhí)行代碼確非常快,大概2分鐘就可以執(zhí)行完成,相差近10倍;如下:
ALTER PROC [dbo].[up_fact_d_gdsclass]
@dst date
as
select
a.c_dt,b.c_adno,b.c_child_adno,b.c_class,b.c_child_class,
a.c_store_id,b.c_type,b.c_tax_rate,
isnull(sum(c.c_order_n),0) as c_number_order,
isnull(sum(c.c_at_order),0) as c_at_order,isnull(sum(a.c_ret_n),0) as c_number_ret,
isnull(sum(a.c_at_in_ret),0) as c_at_ret,isnull(sum(a.c_rec_n),0) as c_number_rec,
isnull(sum(a.c_at_in_rec),0) as c_at_rec,isnull(sum(a.c_move_in_n),0) as c_number_move_in,
。。。。
在一般我們定義存儲過程的變量的時候用上面這種方式;
ALTER PROC [dbo].[up_fact_d_gdsclass]
@dst date
as
declare @dt date
set @dt=@dst
select
a.c_dt,b.c_adno,b.c_child_adno,b.c_class,b.c_child_class,
a.c_store_id,b.c_type,b.c_tax_rate,
isnull(sum(c.c_order_n),0) as c_number_order,
isnull(sum(c.c_at_order),0) as c_at_order,isnull(sum(a.c_ret_n),0) as c_number_ret,
isnull(sum(a.c_at_in_ret),0) as c_at_ret,isnull(sum(a.c_rec_n),0) as c_number_rec,
isnull(sum(a.c_at_in_rec),0) as c_at_rec,isnull(sum(a.c_move_in_n),0) as c_number_move_in,
。。。
當(dāng)在存儲過程中再聲明一個變量來接受外部傳入的這個變量時,執(zhí)行的效率非常高,也可以將內(nèi)部的變量賦一個缺省值;
原因在于:
在SQL Server中有一個叫做 “Parameter sniffing”的特性。SQL Server在存儲過程執(zhí)行之前都會制定一個執(zhí)行計劃。在上面的例子中,SQL在編譯的時候并不知道@thedate的值是多少,所以它在執(zhí)行執(zhí)行計劃的時候就要進行大量的猜測。假設(shè)傳遞給@thedate的參數(shù)大部分都是非空字符串,而FACT表中有40%的thedate字段都是null,那么SQL Server就會選擇全表掃描而不是索引掃描來對參數(shù)@thedate制定執(zhí)行計劃。全表掃描是在參數(shù)為空或為0的時候最好的執(zhí)行計劃。但是全表掃描嚴(yán)重影響了性能。
假設(shè)你第一次使用了Exec pro_ImAnalysis_daily @thedate=’20080312’那么SQL Server就會使用20080312這個值作為下次參數(shù)@thedate的執(zhí)行計劃的參考值,而不會進行全表掃描了,但是如果使用@thedate=null,則下次執(zhí)行計劃就要根據(jù)全表掃描進行了。
有兩種方式能夠避免出現(xiàn)“Parameter sniffing”問題:
(1)通過使用declare聲明的變量來代替參數(shù):使用set @variable=@thedate的方式,將出現(xiàn)@thedate的sql語句全部用@variable來代替。
(2) 將受影響的sql語句隱藏起來,比如:
a) 將受影響的sql語句放到某個子存儲過程中,比如我們在@thedate設(shè)置成為今天后再調(diào)用一個字存儲過程將@thedate作為參數(shù)傳入就可以了。
b) 使用sp_executesql來執(zhí)行受影響的sql。執(zhí)行計劃不會被執(zhí)行,除非sp_executesql語句執(zhí)行完。
c) 使用動態(tài)sql(”EXEC(@sql)”來執(zhí)行受影響的sql。
由此提升了BI在抽取和聚合大數(shù)據(jù)時的效率。
參考:http://www.cnblogs.com/wuming/archive/2009/05/06/1450980.html