2016-06-28 21 views

回答

7

特設計劃和預備計劃有什麼區別?

即席查詢:

select * from t1 

準備好的查詢:
查詢其替代佔位符代替實際值被稱爲準備語句。

一些例子:從維基百科

select * from t1 where [email protected] 

一個例子:

command.CommandText = "SELECT * FROM users WHERE USERNAME = @username AND ROOM = @room"; 

    command.Parameters.AddWithValue("@username", username); 
    command.Parameters.AddWithValue("@room", room); 

我應該知道它什麼努力優化的SQL Server計劃緩存是什麼時候?

有寫關於如何優化計劃cache.so我會盡量少保持白皮書..

通常,當針對SQL執行一個查詢,SQL編譯計劃中的計劃,並將其存儲高速緩存。這種從緩衝池計劃緩存內存和採取不同的版本對how much amount of memory will be used

你知道,內存是一種寶貴的資源,沒有硬件的量就足夠了,如果你有泄漏不同的限制..

假設你提交查詢只有一次或兩次,你往往會提出這樣一個查詢將lot.SQL存儲此查詢在計劃緩存一般漲大PlanCache這是壞的計劃

有不同的DMV,這將有助於你在通過計劃緩存進行挖掘..

查詢找到不同類型的對象都在計劃緩存:

select 
objtype,count(*) as countt,sum(size_in_bytes)*1024.0 as memoryinkb 
from sys.dm_exec_cached_plans a 
group by objtype 

即席,這是腹脹plancache和準備好的查詢只使用一次:

select q.query_hash, 
    q.number_of_entries, 
    t.text as sample_query, 
    p.query_plan as sample_plan 
from (select top 20 query_hash, 
      count(*) as number_of_entries, 
      min(sql_handle) as sample_sql_handle, 
      min(plan_handle) as sample_plan_handle 
     from sys.dm_exec_query_stats 
     group by query_hash 
     having count(*) > 1 
     order by count(*) desc) as q 
    cross apply sys.dm_exec_sql_text(q.sample_sql_handle) as t 
    cross apply sys.dm_exec_query_plan(q.sample_plan_handle) as p 

要刪除正在膨脹計劃緩存的語句:

DECLARE @MB decimal(19,3) 
     , @Count bigint 
     , @StrMB nvarchar(20) 


SELECT @MB = sum(cast((CASE WHEN usecounts = 1 AND objtype IN ('Adhoc', 'Prepared') THEN size_in_bytes ELSE 0 END) as decimal(12,2)))/1024/1024 
     , @Count = sum(CASE WHEN usecounts = 1 AND objtype IN ('Adhoc', 'Prepared') THEN 1 ELSE 0 END) 
     , @StrMB = convert(nvarchar(20), @MB) 
FROM sys.dm_exec_cached_plans 


IF @MB > 10 
     BEGIN 
       DBCC FREESYSTEMCACHE('SQL Plans') 
       RAISERROR ('%s MB was allocated to single-use plan cache. Single-use plans have been cleared.', 10, 1, @StrMB) 
     END 
ELSE 
     BEGIN 
       RAISERROR ('Only %s MB is allocated to single-use plan cache – no need to clear cache now.', 10, 1, @StrMB) 
       — Note: this is only a warning message and not an actual error. 
     END 
go 

上面應該給你從哪裏開始的想法,下面是必須閱讀題目和參考:

1. http://www.sqlskills.com/blogs/kimberly/category/plan-cache/

2. http://sqlblog.com/blogs/kalen_delaney/archive/2007/11/04/did-you-know-sp2-does-not-limit-the-amount-of-plan-cache-you-can-have.aspx

3. https://technet.microsoft.com/en-us/library/dd672789(v=sql.100).aspx

4. Must read article By SQLCAT on issues customer faced while using Prepare Statements

在參考文章上面,建議啓用優化的臨時工作負載選項,但我建議先測試它。有一個interesting thread對DBA.SE

+0

謝謝,很好的答案。自從你開始詳細介紹膨脹plancache與臨時和準備計劃,只用一次。 SQL Server爲ad hoc工作負載提供了優化選項。通過將該選項設置爲1,在第一次執行時,數據庫引擎僅在計劃緩存中存儲小型編譯計劃存根,而不是完整計劃。 – r0tt

+0

多數民衆贊成在很好的選擇,請參閱我更新的答案鏈接的一些線程優化爲即席工作負載選項 – TheGameiswar